一、設置垃圾收集器的參數
-XX:+UseSerialGC,虛擬機在Client模式下的默認值,Serial+Serial Old
-XX:+UseParNewGC,ParNew+Serial Old,在JDK1.8中已經不推薦使用並且將被移除(Java HotSpot(TM) Client VM warning: Using the ParNew young collector with the Serial old collector is deprecated and will likely be removed in a future release)。
-XX:+UseConcMarkSweepGC,ParNew+CMS+Serial Old(CMS執行失敗時會切換到Serial Old)
-XX:+UseParallelGC ,虛擬機在Server模式下的默認值,Parallel Scavenge+Serial Old
-XX:+UseParallelOldGC ,Parallel Scavenge+Parallel Old
-XX:+UseG1GC,G1 Young Generation+G1 Old Generation
二、使用Java代碼測試
public class GCTest {
public static void main(String[] args) {
//-XX:+UseParallelOldGC和-XX:+UseParallelGC結果一樣,因為MXBean名字一樣,但是實際使用的不一樣
List<GarbageCollectorMXBean> garbageCollectorMXBeans = ManagementFactory.getGarbageCollectorMXBeans();
for(GarbageCollectorMXBean gc:garbageCollectorMXBeans){
System.out.println(gc.getName());
System.out.println("--");
}
}
}
我這里使用JDK1.8測試,啟動時輸入JVM參數-XX:+PrintCommandLineFlags,該參數會打印JVM默認的優化參數。
測試結果:
1、指定參數-XX:+PrintCommandLineFlags -XX:+UseSerialGC
-XX:InitialHeapSize=16777216 -XX:MaxHeapSize=268435456 -XX:+PrintCommandLineFlags -XX:-UseLargePagesIndividualAllocation -XX:+UseSerialGC Copy -- MarkSweepCompact --
2、指定參數-XX:+PrintCommandLineFlags -XX:+UseParNewGC
-XX:InitialHeapSize=16777216 -XX:MaxHeapSize=268435456 -XX:+PrintCommandLineFlags -XX:-UseLargePagesIndividualAllocation -XX:+UseParNewGC ParNew -- MarkSweepCompact -- Java HotSpot(TM) Client VM warning: Using the ParNew young collector with the Serial old collector is deprecated and will likely be removed in a future release
3、指定參數-XX:+PrintCommandLineFlags -XX:+UseConcMarkSweepGC
-XX:InitialHeapSize=16777216 -XX:MaxHeapSize=268435456 -XX:MaxNewSize=89481216 -XX:MaxTenuringThreshold=6 -XX:OldPLABSize=16 -XX:+PrintCommandLineFlags -XX:+UseConcMarkSweepGC -XX:-UseLargePagesIndividualAllocation -XX:+UseParNewGC ParNew -- ConcurrentMarkSweep --
4、指定參數-XX:+PrintCommandLineFlags -XX:+UseParallelGC
-XX:InitialHeapSize=16777216 -XX:MaxHeapSize=268435456 -XX:+PrintCommandLineFlags -XX:-UseLargePagesIndividualAllocation -XX:+UseParallelGC PS Scavenge -- PS MarkSweep --
5、指定參數-XX:+PrintCommandLineFlags -XX:+UseParallelOldGC
-XX:InitialHeapSize=16777216 -XX:MaxHeapSize=268435456 -XX:+PrintCommandLineFlags -XX:-UseLargePagesIndividualAllocation -XX:+UseParallelOldGC PS Scavenge -- PS MarkSweep --
6、指定參數-XX:+PrintCommandLineFlags -XX:+UseG1GC
-XX:InitialHeapSize=16777216 -XX:MaxHeapSize=268435456 -XX:+PrintCommandLineFlags -XX:+UseG1GC -XX:-UseLargePagesIndividualAllocation G1 Young Generation -- G1 Old Generation --
三、使用內置JConsle查看
1、寫一個一直運行的代碼
public class GCTest { public static void main(String[] args) throws InterruptedException { while (true) { Thread.sleep(1000); } } }
2、打開命令行,輸入jconsole
3、顯示連接的Java程序
4、查看VM概要
5、也可以在MBean中查看
四、總結
-XX:+UseParallelGC和-XX:+UseParallelOldGC除了JVM參數不同,打印結果都一樣,是因為設置了相同的MXBean名稱,具體可以看一下這一篇文章:https://www.cnblogs.com/kelthuzadx/p/10924117.html