SlideShare a Scribd company logo
1 of 103
Sun JDK 1.6 GC(Garbage Collector)  bluedavy http://blog.bluedavy.com 2010-05-13 V0.2  2010-05-19 V0.5 2010-06-21 V0.8 2010-08-03 V0.9
Java:Auto Memory Management whyneed learn GC? OOM?  An unexpected long pause? GC occur frequently?
We’ll learn gc can be used in jdk 1.6 how to use these gc what difference between these gc when gc will be executed how to solve oom how to monitor gc how to tuning gc how to realiazegc
GC:Garbage Collector not only for gc collection also for memory allocate
Basic Concept—runtime data area -Xss PCregister local method stack local var -XX:PermSize –XX:MaxPermSize oper stack method area stack frame heap JVMmethod stack -Xms -Xmx
Basic concept—memory allocation 1、mostly from heap such as Object o=new Object();       2、from stack native type variable  3、outside heap DirectByteBuffer or use Unsafe.allocateMemory     or some jdk class such as Deflater/Inflater     or jni
Basic concept—garbage collection GC collect memory assumed by “dead” objects. 1. Hotspot think no reference object is a “dead” object 2. Hotspot has four reference types Strong、Soft、Weak、Phantom
Basic concept—generations A research report provided by IBM shows about 80% -- 95% objects are temp objects,so Hotspot split the heap to two  generations.
Basic concept—two generations -Xmn New Generation Eden S0 S1 Old Generation -XX:SurvivorRatio note 1:There are mostly temp objects in new generation,so hotspot use copy Algorithm to collect,then split new gen to eden and two equal survivor space. note 2: The collection for new gen usally called minor gc; the collection for old gen usally           called major gc or full gc (because commonly it need to scan new/old gen and            perm gen, except CMS).
some tips: 1、when system running,we can use jstat –gcutilto monitor the memory changes in parts(such as s0/s1/eden/old); 2、add -XX:+PrintGCDetails –Xloggc:<file> to startup args,then we can see gc status in this file; 3、jmap –heap or jstat –gc to see parts memory capacity & consumption.
how many minor gc type?  & full gc type?
Minor GC Serial Parallel Scavenge ParNew Major GC Serial MSC Parallel MSC CMS Parallel Compacting
We’ll learn gc can be used in jdk 1.6 how to use these gc what difference between these gc when gc will be executed how to solve oom how to monitor gc how to tuning gc how to realiazegc √
Minor GC Serial Parallel Scavenge ParNew which one should I choose?
Minor GC—Serial 1. client class machine default,also can use -XX:+UseSerialGC; 2. eden/s0/s1capacity use -XX:SurvivorRatioto control,    default value is 8,meaning is eden:s0.
Minor GC—Serial mostly allocate on TLABor eden,only two situations below will  allocate on old: 1、need allocate space > eden space; 2、when add PretenureSizeThreshold,need allocate space > PretenureSizeThreshold.  public class SerialGCDemo{     public static void main(String[] args) throws Exception{         byte[] bytes=new byte[1024*1024*2];         byte[] bytes2=new byte[1024*1024*2];         byte[] bytes3=new byte[1024*1024*2]; Thread.sleep(3000);         byte[] bytes4=new byte[1024*1024*4]; Thread.sleep(3000);     } } -Xms20M –Xmx20M –Xmn10M –XX:+UseSerialGC -Xms20M –Xmx20M –Xmn10M -XX:PretenureSizeThreshold=3145728 –XX:+UseSerialGC
Minor GC—Serial gc occurs when eden space is not enough. public class SerialGCDemo{     public static void main(String[] args) throws Exception{         byte[] bytes=new byte[1024*1024*2];         byte[] bytes2=new byte[1024*1024*2];         byte[] bytes3=new byte[1024*1024*2]; System.out.println(“step 1");         byte[] bytes4=new byte[1024*1024*2]; Thread.sleep(3000); System.out.println(“step 2");         byte[] bytes5=new byte[1024*1024*2];         byte[] bytes6=new byte[1024*1024*2]; System.out.println(“step 3");         byte[] bytes7=new byte[1024*1024*2]; Thread.sleep(3000);         } } -Xms20M –Xmx20M –Xmn10M –XX:+UseSerialGC
Minor GC—Serial The example executes cause one minor gc and one full gc,because this rule: before gc,serialgc will test if average space when minor gc from eden promotion to old > old gen free space, if true,thenfull,iffalse,then base on HandleProtomotionFailure value.
Minor GC—Serial  public class SerialGCDemo{     public static void main(String[] args) throws Exception{         byte[] bytes=new byte[1024*1024*2];         byte[] bytes2=new byte[1024*1024*2];         byte[] bytes3=new byte[1024*1024*2]; System.out.println("step 1");         bytes=null;         byte[] bytes4=new byte[1024*1024*2]; Thread.sleep(3000); System.out.println("step 2");         byte[] bytes5=new byte[1024*1024*2];         byte[] bytes6=new byte[1024*1024*2];         bytes4=null;         bytes5=null;         bytes6=null; System.out.println("step 3");         byte[] bytes7=new byte[1024*1024*2]; Thread.sleep(3000);         } } -Xms20M –Xmx20M –Xmn10M –XX:+UseSerialGC -Xms20M –Xmx20M –Xmn10M -XX:-HandlePromotionFailure –XX:+UseSerialGC
Minor GC—Serial The example execute different when use two type args,because this rule: when minor gc occurs: average space when minor gc from eden promotion to old < old gen free space < eden+from capacity if HandlePromotionFailure=true,then minor gcoccurs,iffalse,then full gc occurs.
Minor GC—Serial The rule for new gen promotion to old gen. 1. the object still alive after some times minor gc;     based on MaxTenuringThreshold,default value is 15. 2. to space is not enough,then direct to old.
Minor GC—Serial public class SerialGCThreshold{    public static void main(String[] args) throws Exception{ SerialGCMemoryObject object1=new SerialGCMemoryObject(1); SerialGCMemoryObject object2=new SerialGCMemoryObject(8); SerialGCMemoryObject object3=new SerialGCMemoryObject(8); SerialGCMemoryObject object4=new SerialGCMemoryObject(8);        object2=null;        object3=null; SerialGCMemoryObject object5=new SerialGCMemoryObject(8); Thread.sleep(4000);        object2=new SerialGCMemoryObject(8);        object3=new SerialGCMemoryObject(8);        object2=null;        object3=null;        object5=null; SerialGCMemoryObject object6=new SerialGCMemoryObject(8); Thread.sleep(5000);    } } class SerialGCMemoryObject{    private byte[] bytes=null;    public SerialGCMemoryObject(int multi){       bytes=new byte[1024*256*multi];    } } -Xms20M –Xmx20M –Xmn10M –XX:+UseSerialGC -Xms20M –Xmx20M –Xmn10M –XX:+UseSerialGC -XX:MaxTenuringThreshold=1
Minor GC—Serial change the object1 code: SerialGCMemoryObject object1=new SerialGCMemoryObject(2); -Xms20M –Xmx20M –Xmn10M –XX:+UseSerialGC
Minor GC—Serial The example shows object1 direct to oldwhen the second minor gc occurs, because this rule: after minor gc, then TenuringThreshold will be recaculted. (the first time TenuringThreshold= MaxTenuringThreshold) caculate rule: sum the bytes in per age,when the sum value > to space half,minor(age, MaxTenuringThreshold) can use PrintTenuringDistribution to see TenuringThreshold: Desired survivor size 524288 bytes, new threshold 1 (max 15). so MaxTenuringThreshold only represents max tenuringthreshold.
Minor GC—Serial  [GC [DefNew: 11509K->1138K(14336K), 0.0110060 secs] 11509K->1138K(38912K),      0.0112610 secs] [Times: user=0.00 sys=0.01, real=0.01 secs]
Minor GC—ParNew when use cmsgc,this is default,also can use  -XX:+UseParNewGC to use; 2. eden/s0/s1 capacity controlled by -XX:SurvivorRatio,the default    value is 8,meaning eden:s0. ParNew memory allocation and gc is same as Serial,only difference is ParNew use multi threads to gc,but if add  -XX:+UseAdaptiveSizePolicy,then many differences.
Minor GC—ParNew   [GC [ParNew: 11509K->1152K(14336K), 0.0129150 secs] 11509K->1152K(38912K),    0.0131890 secs] [Times: user=0.05 sys=0.02, real=0.02 secs] if add -XX:+UseAdaptiveSizePolicy to startup args,then output:   [GC [ASParNew: 7495K->120K(9216K), 0.0403410 secs] 7495K->7294K(19456K), 0.0406480 secs] [Times: user=0.06 sys=0.15, real=0.04 secs]
Minor GC—PS server class machine default,also can add -XX:+UseParallelGC to use; eden/s0/s1 capacity can be controlled by InitialSurvivorRatioor SurvivorRatio,when no above two args,then use InitialSurvivorRatio,the default value is 8,but its meaning isnew gen:survivor.
Minor GC—PS mostly allocate on TLAB or eden.  public class PSGCDemo{     public static void main(String[] args) throws Exception{         byte[] bytes=new byte[1024*1024*2];         byte[] bytes2=new byte[1024*1024*2];         byte[] bytes3=new byte[1024*1024*2]; Thread.sleep(3000);         byte[] bytes4=new byte[1024*1024*4]; Thread.sleep(3000);     } } -Xms20M –Xmx20M –Xmn10M –XX:SurvivorRatio=8 –XX:+UseParallelGC
Minor GC—PS The example shows bytes4 object allocate on old gen, because this rule: when allocate fail on TLAB、eden,test if allocate space>= half of eden space,iftrue,then allocate on old gen.
Minor GC—PS when eden space is not enough,and not allocate on old,thengc occurs. public class PSGCDemo{     public static void main(String[] args) throws Exception{         byte[] bytes=new byte[1024*1024*2];         byte[] bytes2=new byte[1024*1024*2];         byte[] bytes3=new byte[1024*1024*2]; System.out.println(“step 1");         byte[] bytes4=new byte[1024*1024*2]; Thread.sleep(3000); System.out.println(“step 2");         byte[] bytes5=new byte[1024*1024*2];         byte[] bytes6=new byte[1024*1024*2]; System.out.println(“step 3");         byte[] bytes7=new byte[1024*1024*2]; Thread.sleep(3000);         } } -Xms20M –Xmx20M –Xmn10M –XX:SurvivorRatio=8 –XX:+UseParallelGC -XX:+PrintGCDetails –XX:verbose:gc
Minor GC—PS the example shows one minor gc and two full gc,because this rule: 1. before gc,serialgc will test if average space when minor gcfrom eden promotion to old > old gen free space, if true,thenfull; 2. after gc,also do above test.
Minor GC—PS The rule for new gen promotion to old gen. 1. the object still alive after some times minor gc: AlwaysTenure, the default value is false,meaning the alive objects will be promoted to old when minor gc. NeverTenure, the default value isfalse,meaning the alive objectswill never be promoted to old,except the to space is not enough. if the above two args are false and UseAdaptiveSizePolicy,then the first time based onInitialTenuringThreshold,but will be adjusted after     every minor gc,if not UseAdaptiveSizePolicy,then based onMaxTenuringThreshold. 2. to space is not enough,then direct to old gen.
Minor GC—PS After minor gc,ifUseAdaptiveSizePolicy,it’ll adjust eden space and to  space based on runtime data,if don’t want to be adjusted,then add -XX:-UseAdaptiveSizePolicyto startup args.
Minor GC—PS [GC [PSYoungGen: 11509K->1184K(14336K)] 11509K->1184K(38912K), 0.0113360 secs]    [Times: user=0.03 sys=0.01, real=0.01 secs]
Major GC Serial MSC Parallel MSC CMS Parallel Compacting which one should I choose?
Major GC—Serial client class machine default,also can add -XX:+UseSerialGC to startup args to use.
Major GC—Serial when occurs 1. old genis not enough; 2. perm gen is not enough; 3. the pessimistic rule when minor gc; 4. heap dump; 5. the code call System.gc,can use -XX:+DisableExplicitGC to     disable.
Major GC—Serial [Full GC [Tenured: 9216K->4210K(10240K), 0.0066570 secs] 16584K->4210K(19456K), [Perm : 1692K->1692K(16384K)], 0.0067070 secs] [Times: user=0.00 sys=0.00, real=0.01 secs]
Major GC—Parallel MSC 1. server class machine default,also can add -XX:+UseParallelGC    to use; 2. parallel threads cpu core<=8 ? cpu core : 3+(cpu core*5)/8 or use -XX:ParallelGCThreads=x to set.
Major GC—Parallel MSC occur rule is same as Serial. note: if ScavengeBeforeFullGCis true(the default value),         then execute minor GCfirst.
Major GC—Parallel MSC [Full GC [PSYoungGen: 1208K->0K(8960K)] [PSOldGen: 6144K->7282K(10240K)] 7352K->7282K(19200K) [PSPermGen: 1686K->1686K(16384K)], 0.0165880 secs] [Times: user=0.01 sys=0.01, real=0.02 secs]
Major GC—Parallel Compacting 1. can add -XX:+UseParallelOldGCto use; 2. parallel threads: cpu core<=8 ? cpu core : 3+(cpu core*5)/8 or use -XX:ParallelGCThreads=xto set.
Major GC—Parallel Compacting occur rule is same as Parallel MSC.
Major GC—Parallel Compacting [Full GC [PSYoungGen: 1224K->0K(8960K)] [ParOldGen: 6144K->7282K(10240K)] 7368K->7282K(19200K) [PSPermGen: 1686K->1685K(16384K)], 0.0223510 secs] [Times: user=0.02 sys=0.06, real=0.03 secs]
Major GC—CMS 1. can add -XX:+UseConcMarkSweepGC to use; 2. mostly concurrent; 3. concurrent threads:    (parallel gc threads +3)/4    or use–XX:ParallelCMSThreads=X to set.
Major GC—CMS occur rule 1. when old gen used reach a percentage; default is 92%,can add PrintCMSInitiationStatistics(cann’t use in 1.5)to see default value,the default value caculate rule:  ((100 - MinHeapFreeRatio) +(double)(CMSTriggerRatio * MinHeapFreeRatio) / 100.0)/ 100.0;MinHeapFreeRatiodefault value: 40   CMSTriggerRatiodefault value: 80 or use CMSInitiatingOccupancyFraction to set; 2. when perm gen used reach a percentage;      perm gen use cms need to add: -XX:+CMSClassUnloadingEnabled default is 92%,default value caculate rule: ((100 - MinHeapFreeRatio) +(double)(CMSTriggerPermRatio* MinHeapFreeRatio) / 100.0)/ 100.0; MinHeapFreeRatiodefault value:40    CMSTriggerPermRatiodefault value: 80  or use CMSInitiatingPermOccupancyFractionto set;
Major GC—CMS occur rule 3. Hotspot decide when to executeCMS GCbased on runtime data; or to use -XX:+UseCMSInitiatingOccupancyOnly to disable this rule; 4. the code call System.gc when set ExplicitGCInvokesConcurrentto     true;     note: when use this and NIO,maybe occur the bug.
Major GC—CMS public class CMSGCOccur{     public static void main(String[] args) throws Exception{         byte[] bytes=new byte[1024*1024*2];          byte[] bytes1=new byte[1024*1024*2];         byte[] bytes2=new byte[1024*1024*2];          byte[] bytes3=new byte[1024*1024*1];          byte[] bytes4=new byte[1024*1024*2]; Thread.sleep(5000);     } } -Xms20M –Xmx20M –Xmn10M -XX:+UseConcMarkSweepGC -XX:+UseCMSInitiatingOccupancyOnly  -XX:+PrintGCDetails -Xms20M –Xmx20M –Xmn10M -XX:+UseConcMarkSweepGC -XX:+PrintGCDetails
Major GC—CMS 1. Promotion Failed when minor gc,to spaceis not enough,then promotion to old,but old is not enough too,then promotion failed;solution: increase to space,increase old space,             or decrease cmsgc occur percentage.     2. Concurrent mode failure when need allocate on old,butcmsgc is running,then      concurrent mode failure,and to keep safe,hotspot will     execute serial full gc;solution:increase old space,                  or decrease cmsgc occur percentage.
Major GC—CMS [GC [1 CMS-initial-mark: 13433K(20480K)] 14465K(29696K), 0.0001830 secs]  [Times: user=0.00 sys=0.00, real=0.00 secs] [CMS-concurrent-mark: 0.004/0.004 secs] [Times: user=0.01 sys=0.00, real=0.01 secs]  [CMS-concurrent-preclean: 0.000/0.000 secs] [Times: user=0.00 sys=0.00, real=0.00 secs]  CMS: abort preclean due to time [CMS-concurrent-abortable-preclean: 0.007/5.042 secs]  [Times: user=0.00 sys=0.00, real=5.04 secs]  [GC[YG occupancy: 3300 K (9216 K)][Rescan (parallel) , 0.0002740 secs] [weak refs processing, 0.0000090 secs]  [1 CMS-remark: 13433K(20480K)] 16734K(29696K), 0.0003710 secs]  [Times: user=0.00 sys=0.00, real=0.00 secs]  [CMS-concurrent-sweep: 0.000/0.000 secs] [Times: user=0.00 sys=0.00, real=0.00 secs]  [CMS-concurrent-reset: 0.000/0.000 secs] [Times: user=0.00 sys=0.00, real=0.00 secs] when add -XX:+UseAdaptiveSizePolicy,then output CMS will change to ASCMS CMS GC Log
GC—Default
GC—Collocation
JDKGC—Beautiful Future Garbage First
We’ll learn gc can be used in jdk 1.6 how to use these gc what difference between these gc when gc will be executed how to solve oom how to monitor gc how to tuning gc how to realiazegc √ √ question: how to let minor gc use psgc,and major gc use parallel compacting gc? √ question:what is difference between psgcand parnewgc? √ question: pls write a code,when it execute first occur 5 minor gc,and 2 full gc,and 2 minor gc,finally 1 full gc.
Let’s solve some OOM Case
OOM Cases 1、java -Xms20m -Xmx20m -Xmn10m -XX:+UseParallelGC 	com. bluedavy.oom.JavaHeapSpaceCase1 2、java -Xms20m -Xmx20m -Xmn10m      -XX:+HeapDumpOnOutOfMemoryError     com.bluedavy.oom.JavaHeapSpaceCase2 3、execute com.bluedavy.oom.JavaHeapSpaceCase3 4、 execute com.bluedavy.oom.JavaHeapSpaceCase4 5、java -Xms1536m -Xmx1536m -Xss100m com.bluedavy.oom.CannotCreateThreadCase
OOMtype the above examples show: 1、java.lang.OutOfMemoryError: GC overhead limit exceeded 2、java.lang.OutOfMemoryError: Java heap space 3、java.lang.OutOfMemoryError: unable to create new native thread and also belows: 4、java.lang.OutOfMemoryError: request bytes for . Out of swap space? two reason: memory is not enough; address space exhausted(for      example on 32 bit linux the process can only use 3G address space) this OOMwill cause Java process exit; monitor who use native memory: google-perftools 5、java.lang.OutOfMemoryError: PermGen space PermGenis not enough;
OOMsolution Java Heap SpaceOOM: 1. add -XX:+HeapDumpOnOutOfMemoryError; 2. jmap–histo; 3. jmap –dump; 4. hand to solve; 5. heap too small? Out of swap: 1. heap too large? 2. Google perftools,if not help,then no way... unable to create new native thread: 1. too many threads; 2. –Xss; PermGen space: 1. PermGentoo small? 2. too many ClassLoaders?
OOM Reference 1. Sun JDK 6 troubleshooting Guide; 2.OOM
GCMonitor 1. jstat–gcutil [pid] [intervel] [count] 2. -verbose:gc      -XX:+PrintGCDetails      -XX:+PrintGCApplicationStoppedTime      -XX:+PrintGCDateStamps      -XX:+PrintHeapAtGC      -Xloggc:[file] gclog can be analised by GCLogVieweror gchisto. 3. if support GUI,then can use visualvm.
who consume the memory 1. alive long situation,easy,jmap –dump,then MAT; 2. alive short,if no GUI,thenin trouble,ifGUI,thenjprofiler/visualvm.
We’ll learn gc can be used in jdk 1.6 how to use these gc what difference between these gc when gc will be executed how to solve oom how to monitor gc how to tuning gc how to realiazegc √ √ √ √ √ java.lang.OutOfMemoryError: Java Heap Space,what can we do? √ pls tell me how many minor gc and full gc the app executes.
tuning case 4 cpu,os: linux 2.6.18 32 bit startup args -server -Xms1536m -Xmx1536m –Xmn700m gc log: 67919.817: [GC [PSYoungGen: 588706K->70592K(616832K)] 1408209K->906379K(1472896K),                   0.0197090 secs] [Times: user=0.06 sys=0.00, real=0.02 secs] 67919.837: [Full GC [PSYoungGen: 70592K->0K(616832K)]                   [PSOldGen: 835787K->375316K(856064K)] 906379K->375316K(1472896K)                   [PSPermGen: 64826K->64826K(98304K)], 0.5478600 secs]                   [Times: user=0.55 sys=0.00, real=0.55 secs]
tuning case minor gc info
tuning case gc log: 68132.862: [GC [PSYoungGen: 594736K->63715K(609920K)] 1401225K->891090K(1465984K),                   0.0309810 secs] [Times: user=0.06 sys=0.01, real=0.04 secs]  68132.893: [Full GC [PSYoungGen: 63715K->0K(609920K)]                  [PSOldGen: 827375K->368026K(856064K)] 891090K->368026K(1465984K)                  [PSPermGen: 64869K->64690K(98304K)], 0.5341070 secs]                  [Times: user=0.53 sys=0.00, real=0.53 secs] then repeat.
tuning case Goal decrease full gc frequency and pause time caused by gc. Method decrease response time or requests,difficult; decrease memory used per request,difficult; decrease memory promoted to old every minor gc,it’s ok;
tuning case decrease memory promoted to old every minor gc increase new gen space,now new gen space is big,soit does not work; increase survivor space,it maybe works.
tuning case increase Survivor space now PS GC,so survivor space is adjusted,but monitor this case,we can see mostly survivor space only have 1—4MB,it’s too small; so add -XX:-UseAdaptiveSizePolicy; caculate survivor spaceneed size see current to space size,and after minor gc,old gen increased size,then to space+old gen increased size will be survivor space need size; sum many times then average; adjust survivor space to desired size; after the adjustion,minorgcmore,but full gc decrease to every two hours.
tuning case the method decrease full gcfrequency,but the pause time caused by gc only decrease 10%; keep Survivorspace,and use cms,the final startup args: -Xms1536m -Xmx1536m -Xmn700m -XX:SurvivorRatio=7 -XX:+UseConcMarkSweepGC-XX:CMSMaxAbortablePrecleanTime=1000 -XX:+CMSClassUnloadingEnabled-XX:+DisableExplicitGC
GC Tuning
GC Tuning—common policy decrease full gc frequency–common problem oldgen used too high;common reason: cache too many objects;for example: preparedstatement cacheset too big when use oracle driver;solution: dump then mat,bingo!
GC Tuning—common policy decrease full gc frequency–common problem  many objects promotion to old gen;common reason: survivor spacetoo small;           response time is too slow;                                    many memory used by per request;solution:  decrease minor gc frequency;                          let object collect when minor gc,such as                           increase suvivorspace,new gen;                          use cmsgc;tuning application;
GC Tuning—common policy decrease full gc time common reason:old gen is too big;solution:       parallel gc?decrease heap or old gen;       add cpu or upgrade cpu.
GC Tuning—common policy decrease minor gc frequency common reasonminor gc too small;          many memory used by per request;solutionincrease heap,new or eden;      decrease memory used by per request.
GC Tuning—common policy decrease minor gc time      common reason                    response time too slowwsolutionadd cpu or upgrade cpu;     if u use cmsgc,then as much as possible avoid object          allocate or  promote to old gen,or change to psgc.
GC Tuning GC Tuning is art! The final solution is decrease  response time or memory used per  request; or upgrade to 64 bit,then use large heap,of course it needs more cpu.
We’ll learn gc can be used in jdk 1.6 how to use these gc what difference between these gc when gc will be executed how to solve oom how to monitor gc how to tuning gc how to realiazegc √ √ √ √ √ √ √
Garbage Collection 1. usually use below two methods:1.1 Reference counter not suitable for complex object reference situations; count will decrease performance; good point is when counters decrease to zero,then collect.     1.2 Tracing hotspot use; need pause the application.           common algithorm: Copying/Mark-Sweep/Mark-Compact
Garbage Collection Hotspot scan objects from root set; root set 1. current running thread; 2. public or static variables; 3. JVM Handles; 4. JNIHandles;
Garbage Collection how to pause thread?safepointfirst: test a memory page readable; keypoint:only the code will cause the reference change need     pause; so when gcoccurs,it’ll submit a request to core,then core      set the memory page cannot read,when code execute reach safepoint,then pause.
Minor GC Serial Parallel Scavenge ParNew
Minor GC allocate on a continous space and use bump the pointer. A B C D
Minor GC the policy: scan new gen objects,   find alive objects; use copying algorithm   to finish collection.
Minor GC because minor gc only scan new gen,if old gen references new  gen,how to do?when assign a reference value,will pass a write barrier;test if old gen ref new gen object,iftrue,then record to      remember set;when minor gc,the objects in remember set also put into     root set.
Major GC Serial MSC Parallel MSC CMS Parallel Compacting
Major GC—Serial Memory allocation policy 1. not support TLAB; 2. bump pointer.
Major GC—Serial Garbage Collection Policy based on Mark Sweep Compact algorithm. split four phases: 1. mark which object alive; 2. caculate new address; 3. update pointer to new address; 4. move object to new address.
Major GC—Parallel MSC Memory allocation policy bump pointer.
Major GC—Parallel MSC The only difference with serial is multi threads.
Major GC—Parallel Compacting Memory allocation is same as parallel MSC.
Major GC—Parallel Compacting Garbage Collection policy:
Major GC—CMS Memory Allocation Policy 1. first get freelist lock; 2. find which chunk can put the object; 3. if now gc in marking phase,the mark the object alive.
Major GC—CMS start a cms thread first; based on Mark-Sweep,split into five phase;     Initial Marking(Stop-the-world)Concurrent MarkingPreClean(Sun jdk 1.5 added)Final Marking(Stop-the-world)     Concurrent Sweeping
Major GC—CMS Initial Marking (Stop-the-world)markroot setdirect ref objects; Concurrent Markingconcurrent mark phase 1 marked objects recursively;    Mod Union Tableto solve the ref change when minor gc executes;    Card Table      to solve the ref change in the old gen.
Major GC—CMS Preclean     scan again phase 2 marked objects and dirty objects;-XX: CMSScheduleRemarkEdenSizeThreshold、-XX: CMSScheduleRemarkEdenPenetration this step maybe causes bug,when object need allocate old,        but remark phase not execute,then old space not enough,        so current step have a timeout arg,default value is 5000ms,        or use -XX: CMSMaxAbortablePrecleanTime to control.
Major GC—CMS Final  Marking (Stop-the-world)scan Mod Union Table/Card Table,then remark. Concurrent Sweepingcollect the memory used by “dead” objects.
Major GC—CMS good point and weak point; mostly concurrent,so it’ll only pause application little time; float garbage,so need more memory size; memory fragment; fight for cpu,so it not suit for cpu intensive app; multi mark,sogc time is longer then parallel gc; memory allocation need use free list,soit’s slower then bumppointer allocate; concurrent with application,so free list will compete.
Major GC—CMS float garbage
Study SUN JDK V1.6 GC sources download JDK sources; use Source Insightetc. tools to see SerialGC、ParNewGC GenCollectedHeap::mem_allocate PS GC ParallelScavengeHeap::mem_allocate CMS GC ConcurrentMarkSweepThread::run CMSCollector::collect
We’ll learn gc can be used in jdk 1.6 how to use these gc what difference between these gc when gc will be executed how to solve oom how to monitor gc how to tuning gc how to realiazegc √ √ √ √ √ √ √ √
References 1. GC Tuning in the Hotspot 2. Our Collectors 3. CMS GC 4. why now 5. hotspot 6.0 gc tuning 6. memory management in hotspot whitepaper

More Related Content

What's hot

Am I reading GC logs Correctly?
Am I reading GC logs Correctly?Am I reading GC logs Correctly?
Am I reading GC logs Correctly?Tier1 App
 
pgconfasia2016 plcuda en
pgconfasia2016 plcuda enpgconfasia2016 plcuda en
pgconfasia2016 plcuda enKohei KaiGai
 
20160407_GTC2016_PgSQL_In_Place
20160407_GTC2016_PgSQL_In_Place20160407_GTC2016_PgSQL_In_Place
20160407_GTC2016_PgSQL_In_PlaceKohei KaiGai
 
PG-Strom - GPGPU meets PostgreSQL, PGcon2015
PG-Strom - GPGPU meets PostgreSQL, PGcon2015PG-Strom - GPGPU meets PostgreSQL, PGcon2015
PG-Strom - GPGPU meets PostgreSQL, PGcon2015Kohei KaiGai
 
Shared Memory Performance: Beyond TCP/IP with Ben Cotton, JPMorgan
Shared Memory Performance: Beyond TCP/IP with Ben Cotton, JPMorganShared Memory Performance: Beyond TCP/IP with Ben Cotton, JPMorgan
Shared Memory Performance: Beyond TCP/IP with Ben Cotton, JPMorganHazelcast
 
Mastering java in containers - MadridJUG
Mastering java in containers - MadridJUGMastering java in containers - MadridJUG
Mastering java in containers - MadridJUGJorge Morales
 
Gnocchi v3 brownbag
Gnocchi v3 brownbagGnocchi v3 brownbag
Gnocchi v3 brownbagGordon Chung
 
Optimizing Kubernetes Resource Requests/Limits for Cost-Efficiency and Latency
Optimizing Kubernetes Resource Requests/Limits for Cost-Efficiency and LatencyOptimizing Kubernetes Resource Requests/Limits for Cost-Efficiency and Latency
Optimizing Kubernetes Resource Requests/Limits for Cost-Efficiency and LatencyHenning Jacobs
 
Don't dump thread dumps
Don't dump thread dumpsDon't dump thread dumps
Don't dump thread dumpsTier1app
 
Tweaking performance on high-load projects
Tweaking performance on high-load projectsTweaking performance on high-load projects
Tweaking performance on high-load projectsDmitriy Dumanskiy
 
20170602_OSSummit_an_intelligent_storage
20170602_OSSummit_an_intelligent_storage20170602_OSSummit_an_intelligent_storage
20170602_OSSummit_an_intelligent_storageKohei KaiGai
 
Gnocchi v4 (preview)
Gnocchi v4 (preview)Gnocchi v4 (preview)
Gnocchi v4 (preview)Gordon Chung
 
Tarantool как платформа для микросервисов / Антон Резников, Владимир Перепели...
Tarantool как платформа для микросервисов / Антон Резников, Владимир Перепели...Tarantool как платформа для микросервисов / Антон Резников, Владимир Перепели...
Tarantool как платформа для микросервисов / Антон Резников, Владимир Перепели...Ontico
 
Seastar @ NYCC++UG
Seastar @ NYCC++UGSeastar @ NYCC++UG
Seastar @ NYCC++UGAvi Kivity
 
Use Ruby GC in full..
Use Ruby GC in full..Use Ruby GC in full..
Use Ruby GC in full..Alex Mercer
 
Путь мониторинга 2.0 всё стало другим / Всеволод Поляков (Grammarly)
Путь мониторинга 2.0 всё стало другим / Всеволод Поляков (Grammarly)Путь мониторинга 2.0 всё стало другим / Всеволод Поляков (Grammarly)
Путь мониторинга 2.0 всё стало другим / Всеволод Поляков (Grammarly)Ontico
 
Memory, Big Data, NoSQL and Virtualization
Memory, Big Data, NoSQL and VirtualizationMemory, Big Data, NoSQL and Virtualization
Memory, Big Data, NoSQL and VirtualizationBigstep
 
Java gpu computing
Java gpu computingJava gpu computing
Java gpu computingArjan Lamers
 

What's hot (20)

Am I reading GC logs Correctly?
Am I reading GC logs Correctly?Am I reading GC logs Correctly?
Am I reading GC logs Correctly?
 
pgconfasia2016 plcuda en
pgconfasia2016 plcuda enpgconfasia2016 plcuda en
pgconfasia2016 plcuda en
 
20160407_GTC2016_PgSQL_In_Place
20160407_GTC2016_PgSQL_In_Place20160407_GTC2016_PgSQL_In_Place
20160407_GTC2016_PgSQL_In_Place
 
PG-Strom - GPGPU meets PostgreSQL, PGcon2015
PG-Strom - GPGPU meets PostgreSQL, PGcon2015PG-Strom - GPGPU meets PostgreSQL, PGcon2015
PG-Strom - GPGPU meets PostgreSQL, PGcon2015
 
Shared Memory Performance: Beyond TCP/IP with Ben Cotton, JPMorgan
Shared Memory Performance: Beyond TCP/IP with Ben Cotton, JPMorganShared Memory Performance: Beyond TCP/IP with Ben Cotton, JPMorgan
Shared Memory Performance: Beyond TCP/IP with Ben Cotton, JPMorgan
 
[BGOUG] Java GC - Friend or Foe
[BGOUG] Java GC - Friend or Foe[BGOUG] Java GC - Friend or Foe
[BGOUG] Java GC - Friend or Foe
 
Mastering java in containers - MadridJUG
Mastering java in containers - MadridJUGMastering java in containers - MadridJUG
Mastering java in containers - MadridJUG
 
Gnocchi v3 brownbag
Gnocchi v3 brownbagGnocchi v3 brownbag
Gnocchi v3 brownbag
 
Optimizing Kubernetes Resource Requests/Limits for Cost-Efficiency and Latency
Optimizing Kubernetes Resource Requests/Limits for Cost-Efficiency and LatencyOptimizing Kubernetes Resource Requests/Limits for Cost-Efficiency and Latency
Optimizing Kubernetes Resource Requests/Limits for Cost-Efficiency and Latency
 
Don't dump thread dumps
Don't dump thread dumpsDon't dump thread dumps
Don't dump thread dumps
 
Tweaking performance on high-load projects
Tweaking performance on high-load projectsTweaking performance on high-load projects
Tweaking performance on high-load projects
 
20170602_OSSummit_an_intelligent_storage
20170602_OSSummit_an_intelligent_storage20170602_OSSummit_an_intelligent_storage
20170602_OSSummit_an_intelligent_storage
 
Gnocchi v4 (preview)
Gnocchi v4 (preview)Gnocchi v4 (preview)
Gnocchi v4 (preview)
 
Tarantool как платформа для микросервисов / Антон Резников, Владимир Перепели...
Tarantool как платформа для микросервисов / Антон Резников, Владимир Перепели...Tarantool как платформа для микросервисов / Антон Резников, Владимир Перепели...
Tarantool как платформа для микросервисов / Антон Резников, Владимир Перепели...
 
Seastar @ NYCC++UG
Seastar @ NYCC++UGSeastar @ NYCC++UG
Seastar @ NYCC++UG
 
Use Ruby GC in full..
Use Ruby GC in full..Use Ruby GC in full..
Use Ruby GC in full..
 
Путь мониторинга 2.0 всё стало другим / Всеволод Поляков (Grammarly)
Путь мониторинга 2.0 всё стало другим / Всеволод Поляков (Grammarly)Путь мониторинга 2.0 всё стало другим / Всеволод Поляков (Grammarly)
Путь мониторинга 2.0 всё стало другим / Всеволод Поляков (Grammarly)
 
Memory, Big Data, NoSQL and Virtualization
Memory, Big Data, NoSQL and VirtualizationMemory, Big Data, NoSQL and Virtualization
Memory, Big Data, NoSQL and Virtualization
 
Java gpu computing
Java gpu computingJava gpu computing
Java gpu computing
 
Cassandra
CassandraCassandra
Cassandra
 

Viewers also liked

WebLogic Deployment Plan Example
WebLogic Deployment Plan ExampleWebLogic Deployment Plan Example
WebLogic Deployment Plan ExampleJames Bayer
 
Oracle WebLogic Server Basic Concepts
Oracle WebLogic Server Basic ConceptsOracle WebLogic Server Basic Concepts
Oracle WebLogic Server Basic ConceptsJames Bayer
 
WebLogic Developer Webcast 5: Troubleshooting and Testing with WebLogic, Soap...
WebLogic Developer Webcast 5: Troubleshooting and Testing with WebLogic, Soap...WebLogic Developer Webcast 5: Troubleshooting and Testing with WebLogic, Soap...
WebLogic Developer Webcast 5: Troubleshooting and Testing with WebLogic, Soap...Jeffrey West
 
Powering the Cloud with Oracle WebLogic
Powering the Cloud with Oracle WebLogicPowering the Cloud with Oracle WebLogic
Powering the Cloud with Oracle WebLogicLucas Jellema
 
Fusion Middleware 12c Upgrade - Standalone server
Fusion Middleware 12c Upgrade - Standalone serverFusion Middleware 12c Upgrade - Standalone server
Fusion Middleware 12c Upgrade - Standalone serverK Kumar Guduru
 
Java常见问题排查
Java常见问题排查Java常见问题排查
Java常见问题排查bluedavy lin
 

Viewers also liked (6)

WebLogic Deployment Plan Example
WebLogic Deployment Plan ExampleWebLogic Deployment Plan Example
WebLogic Deployment Plan Example
 
Oracle WebLogic Server Basic Concepts
Oracle WebLogic Server Basic ConceptsOracle WebLogic Server Basic Concepts
Oracle WebLogic Server Basic Concepts
 
WebLogic Developer Webcast 5: Troubleshooting and Testing with WebLogic, Soap...
WebLogic Developer Webcast 5: Troubleshooting and Testing with WebLogic, Soap...WebLogic Developer Webcast 5: Troubleshooting and Testing with WebLogic, Soap...
WebLogic Developer Webcast 5: Troubleshooting and Testing with WebLogic, Soap...
 
Powering the Cloud with Oracle WebLogic
Powering the Cloud with Oracle WebLogicPowering the Cloud with Oracle WebLogic
Powering the Cloud with Oracle WebLogic
 
Fusion Middleware 12c Upgrade - Standalone server
Fusion Middleware 12c Upgrade - Standalone serverFusion Middleware 12c Upgrade - Standalone server
Fusion Middleware 12c Upgrade - Standalone server
 
Java常见问题排查
Java常见问题排查Java常见问题排查
Java常见问题排查
 

Similar to Sun jdk 1.6 gc english version

java memory management & gc
java memory management & gcjava memory management & gc
java memory management & gcexsuns
 
Performance tuning jvm
Performance tuning jvmPerformance tuning jvm
Performance tuning jvmPrem Kuppumani
 
7 jvm-arguments-v1
7 jvm-arguments-v17 jvm-arguments-v1
7 jvm-arguments-v1Tier1 app
 
7-JVM-arguments-JaxLondon-2023.pptx
7-JVM-arguments-JaxLondon-2023.pptx7-JVM-arguments-JaxLondon-2023.pptx
7-JVM-arguments-JaxLondon-2023.pptxTier1 app
 
Java 어플리케이션 성능튜닝 Part1
Java 어플리케이션 성능튜닝 Part1Java 어플리케이션 성능튜닝 Part1
Java 어플리케이션 성능튜닝 Part1상욱 송
 
Федор Поляков (Looksery) “Face Tracking на мобильных устройствах в режиме реа...
Федор Поляков (Looksery) “Face Tracking на мобильных устройствах в режиме реа...Федор Поляков (Looksery) “Face Tracking на мобильных устройствах в режиме реа...
Федор Поляков (Looksery) “Face Tracking на мобильных устройствах в режиме реа...Provectus
 
7 jvm-arguments-Confoo
7 jvm-arguments-Confoo7 jvm-arguments-Confoo
7 jvm-arguments-ConfooTier1 app
 
JVM memory management & Diagnostics
JVM memory management & DiagnosticsJVM memory management & Diagnostics
JVM memory management & DiagnosticsDhaval Shah
 
Garbage Collection of Java VM
Garbage Collection of Java VMGarbage Collection of Java VM
Garbage Collection of Java VMYongqiang Li
 
lets-crash-apps-jax-2022.pptx
lets-crash-apps-jax-2022.pptxlets-crash-apps-jax-2022.pptx
lets-crash-apps-jax-2022.pptxTier1 app
 
GPU-Accelerated Parallel Computing
GPU-Accelerated Parallel ComputingGPU-Accelerated Parallel Computing
GPU-Accelerated Parallel ComputingJun Young Park
 
Anima Anadkumar, Principal Scientist, Amazon Web Services, Endowed Professor,...
Anima Anadkumar, Principal Scientist, Amazon Web Services, Endowed Professor,...Anima Anadkumar, Principal Scientist, Amazon Web Services, Endowed Professor,...
Anima Anadkumar, Principal Scientist, Amazon Web Services, Endowed Professor,...MLconf
 
Jvm tuning for low latency application & Cassandra
Jvm tuning for low latency application & CassandraJvm tuning for low latency application & Cassandra
Jvm tuning for low latency application & CassandraQuentin Ambard
 
Optimizing Parallel Reduction in CUDA : NOTES
Optimizing Parallel Reduction in CUDA : NOTESOptimizing Parallel Reduction in CUDA : NOTES
Optimizing Parallel Reduction in CUDA : NOTESSubhajit Sahu
 
RAPIDS: ускоряем Pandas и scikit-learn на GPU Павел Клеменков, NVidia
RAPIDS: ускоряем Pandas и scikit-learn на GPU  Павел Клеменков, NVidiaRAPIDS: ускоряем Pandas и scikit-learn на GPU  Павел Клеменков, NVidia
RAPIDS: ускоряем Pandas и scikit-learn на GPU Павел Клеменков, NVidiaMail.ru Group
 
Exploring Parallel Merging In GPU Based Systems Using CUDA C.
Exploring Parallel Merging In GPU Based Systems Using CUDA C.Exploring Parallel Merging In GPU Based Systems Using CUDA C.
Exploring Parallel Merging In GPU Based Systems Using CUDA C.Rakib Hossain
 
Become a Garbage Collection Hero
Become a Garbage Collection HeroBecome a Garbage Collection Hero
Become a Garbage Collection HeroTier1app
 

Similar to Sun jdk 1.6 gc english version (20)

java memory management & gc
java memory management & gcjava memory management & gc
java memory management & gc
 
Performance tuning jvm
Performance tuning jvmPerformance tuning jvm
Performance tuning jvm
 
7 jvm-arguments-v1
7 jvm-arguments-v17 jvm-arguments-v1
7 jvm-arguments-v1
 
7-JVM-arguments-JaxLondon-2023.pptx
7-JVM-arguments-JaxLondon-2023.pptx7-JVM-arguments-JaxLondon-2023.pptx
7-JVM-arguments-JaxLondon-2023.pptx
 
Java 어플리케이션 성능튜닝 Part1
Java 어플리케이션 성능튜닝 Part1Java 어플리케이션 성능튜닝 Part1
Java 어플리케이션 성능튜닝 Part1
 
Федор Поляков (Looksery) “Face Tracking на мобильных устройствах в режиме реа...
Федор Поляков (Looksery) “Face Tracking на мобильных устройствах в режиме реа...Федор Поляков (Looksery) “Face Tracking на мобильных устройствах в режиме реа...
Федор Поляков (Looksery) “Face Tracking на мобильных устройствах в режиме реа...
 
7 jvm-arguments-Confoo
7 jvm-arguments-Confoo7 jvm-arguments-Confoo
7 jvm-arguments-Confoo
 
JVM memory management & Diagnostics
JVM memory management & DiagnosticsJVM memory management & Diagnostics
JVM memory management & Diagnostics
 
Garbage Collection of Java VM
Garbage Collection of Java VMGarbage Collection of Java VM
Garbage Collection of Java VM
 
lets-crash-apps-jax-2022.pptx
lets-crash-apps-jax-2022.pptxlets-crash-apps-jax-2022.pptx
lets-crash-apps-jax-2022.pptx
 
GPU-Accelerated Parallel Computing
GPU-Accelerated Parallel ComputingGPU-Accelerated Parallel Computing
GPU-Accelerated Parallel Computing
 
Anima Anadkumar, Principal Scientist, Amazon Web Services, Endowed Professor,...
Anima Anadkumar, Principal Scientist, Amazon Web Services, Endowed Professor,...Anima Anadkumar, Principal Scientist, Amazon Web Services, Endowed Professor,...
Anima Anadkumar, Principal Scientist, Amazon Web Services, Endowed Professor,...
 
Enhancing the region model of RTSJ
Enhancing the region model of RTSJEnhancing the region model of RTSJ
Enhancing the region model of RTSJ
 
Jvm tuning for low latency application & Cassandra
Jvm tuning for low latency application & CassandraJvm tuning for low latency application & Cassandra
Jvm tuning for low latency application & Cassandra
 
jvm goes to big data
jvm goes to big datajvm goes to big data
jvm goes to big data
 
Optimizing Parallel Reduction in CUDA : NOTES
Optimizing Parallel Reduction in CUDA : NOTESOptimizing Parallel Reduction in CUDA : NOTES
Optimizing Parallel Reduction in CUDA : NOTES
 
RAPIDS: ускоряем Pandas и scikit-learn на GPU Павел Клеменков, NVidia
RAPIDS: ускоряем Pandas и scikit-learn на GPU  Павел Клеменков, NVidiaRAPIDS: ускоряем Pandas и scikit-learn на GPU  Павел Клеменков, NVidia
RAPIDS: ускоряем Pandas и scikit-learn на GPU Павел Клеменков, NVidia
 
Exploring Parallel Merging In GPU Based Systems Using CUDA C.
Exploring Parallel Merging In GPU Based Systems Using CUDA C.Exploring Parallel Merging In GPU Based Systems Using CUDA C.
Exploring Parallel Merging In GPU Based Systems Using CUDA C.
 
Ping to Pong
Ping to PongPing to Pong
Ping to Pong
 
Become a Garbage Collection Hero
Become a Garbage Collection HeroBecome a Garbage Collection Hero
Become a Garbage Collection Hero
 

More from bluedavy lin

高性能的Java代码编写及常见问题排查
高性能的Java代码编写及常见问题排查高性能的Java代码编写及常见问题排查
高性能的Java代码编写及常见问题排查bluedavy lin
 
Java内存管理问题案例分享
Java内存管理问题案例分享Java内存管理问题案例分享
Java内存管理问题案例分享bluedavy lin
 
HBase@taobao for 技术沙龙
HBase@taobao for 技术沙龙HBase@taobao for 技术沙龙
HBase@taobao for 技术沙龙bluedavy lin
 
Hbase简介与实践分享
Hbase简介与实践分享Hbase简介与实践分享
Hbase简介与实践分享bluedavy lin
 
Sun JDK 1.6内存管理 -调优篇
Sun JDK 1.6内存管理 -调优篇Sun JDK 1.6内存管理 -调优篇
Sun JDK 1.6内存管理 -调优篇bluedavy lin
 
Sun jdk 1.6内存管理 -使用篇
Sun jdk 1.6内存管理 -使用篇Sun jdk 1.6内存管理 -使用篇
Sun jdk 1.6内存管理 -使用篇bluedavy lin
 
并发编程交流
并发编程交流并发编程交流
并发编程交流bluedavy lin
 
OSGi理论与实战
OSGi理论与实战OSGi理论与实战
OSGi理论与实战bluedavy lin
 

More from bluedavy lin (11)

高性能的Java代码编写及常见问题排查
高性能的Java代码编写及常见问题排查高性能的Java代码编写及常见问题排查
高性能的Java代码编写及常见问题排查
 
Java内存管理问题案例分享
Java内存管理问题案例分享Java内存管理问题案例分享
Java内存管理问题案例分享
 
HBase@taobao for 技术沙龙
HBase@taobao for 技术沙龙HBase@taobao for 技术沙龙
HBase@taobao for 技术沙龙
 
Hbase简介与实践分享
Hbase简介与实践分享Hbase简介与实践分享
Hbase简介与实践分享
 
菜鸟看Hbase
菜鸟看Hbase菜鸟看Hbase
菜鸟看Hbase
 
Sun JDK 1.6内存管理 -调优篇
Sun JDK 1.6内存管理 -调优篇Sun JDK 1.6内存管理 -调优篇
Sun JDK 1.6内存管理 -调优篇
 
Sun jdk 1.6内存管理 -使用篇
Sun jdk 1.6内存管理 -使用篇Sun jdk 1.6内存管理 -使用篇
Sun jdk 1.6内存管理 -使用篇
 
JavaOne summary
JavaOne summaryJavaOne summary
JavaOne summary
 
Sun jdk 1.6 gc
Sun jdk 1.6 gcSun jdk 1.6 gc
Sun jdk 1.6 gc
 
并发编程交流
并发编程交流并发编程交流
并发编程交流
 
OSGi理论与实战
OSGi理论与实战OSGi理论与实战
OSGi理论与实战
 

Sun jdk 1.6 gc english version

  • 1. Sun JDK 1.6 GC(Garbage Collector) bluedavy http://blog.bluedavy.com 2010-05-13 V0.2 2010-05-19 V0.5 2010-06-21 V0.8 2010-08-03 V0.9
  • 2. Java:Auto Memory Management whyneed learn GC? OOM? An unexpected long pause? GC occur frequently?
  • 3. We’ll learn gc can be used in jdk 1.6 how to use these gc what difference between these gc when gc will be executed how to solve oom how to monitor gc how to tuning gc how to realiazegc
  • 4. GC:Garbage Collector not only for gc collection also for memory allocate
  • 5. Basic Concept—runtime data area -Xss PCregister local method stack local var -XX:PermSize –XX:MaxPermSize oper stack method area stack frame heap JVMmethod stack -Xms -Xmx
  • 6. Basic concept—memory allocation 1、mostly from heap such as Object o=new Object(); 2、from stack native type variable 3、outside heap DirectByteBuffer or use Unsafe.allocateMemory or some jdk class such as Deflater/Inflater or jni
  • 7. Basic concept—garbage collection GC collect memory assumed by “dead” objects. 1. Hotspot think no reference object is a “dead” object 2. Hotspot has four reference types Strong、Soft、Weak、Phantom
  • 8. Basic concept—generations A research report provided by IBM shows about 80% -- 95% objects are temp objects,so Hotspot split the heap to two generations.
  • 9. Basic concept—two generations -Xmn New Generation Eden S0 S1 Old Generation -XX:SurvivorRatio note 1:There are mostly temp objects in new generation,so hotspot use copy Algorithm to collect,then split new gen to eden and two equal survivor space. note 2: The collection for new gen usally called minor gc; the collection for old gen usally called major gc or full gc (because commonly it need to scan new/old gen and perm gen, except CMS).
  • 10. some tips: 1、when system running,we can use jstat –gcutilto monitor the memory changes in parts(such as s0/s1/eden/old); 2、add -XX:+PrintGCDetails –Xloggc:<file> to startup args,then we can see gc status in this file; 3、jmap –heap or jstat –gc to see parts memory capacity & consumption.
  • 11. how many minor gc type? & full gc type?
  • 12. Minor GC Serial Parallel Scavenge ParNew Major GC Serial MSC Parallel MSC CMS Parallel Compacting
  • 13. We’ll learn gc can be used in jdk 1.6 how to use these gc what difference between these gc when gc will be executed how to solve oom how to monitor gc how to tuning gc how to realiazegc √
  • 14. Minor GC Serial Parallel Scavenge ParNew which one should I choose?
  • 15. Minor GC—Serial 1. client class machine default,also can use -XX:+UseSerialGC; 2. eden/s0/s1capacity use -XX:SurvivorRatioto control, default value is 8,meaning is eden:s0.
  • 16. Minor GC—Serial mostly allocate on TLABor eden,only two situations below will allocate on old: 1、need allocate space > eden space; 2、when add PretenureSizeThreshold,need allocate space > PretenureSizeThreshold. public class SerialGCDemo{ public static void main(String[] args) throws Exception{ byte[] bytes=new byte[1024*1024*2]; byte[] bytes2=new byte[1024*1024*2]; byte[] bytes3=new byte[1024*1024*2]; Thread.sleep(3000); byte[] bytes4=new byte[1024*1024*4]; Thread.sleep(3000); } } -Xms20M –Xmx20M –Xmn10M –XX:+UseSerialGC -Xms20M –Xmx20M –Xmn10M -XX:PretenureSizeThreshold=3145728 –XX:+UseSerialGC
  • 17. Minor GC—Serial gc occurs when eden space is not enough. public class SerialGCDemo{ public static void main(String[] args) throws Exception{ byte[] bytes=new byte[1024*1024*2]; byte[] bytes2=new byte[1024*1024*2]; byte[] bytes3=new byte[1024*1024*2]; System.out.println(“step 1"); byte[] bytes4=new byte[1024*1024*2]; Thread.sleep(3000); System.out.println(“step 2"); byte[] bytes5=new byte[1024*1024*2]; byte[] bytes6=new byte[1024*1024*2]; System.out.println(“step 3"); byte[] bytes7=new byte[1024*1024*2]; Thread.sleep(3000); } } -Xms20M –Xmx20M –Xmn10M –XX:+UseSerialGC
  • 18. Minor GC—Serial The example executes cause one minor gc and one full gc,because this rule: before gc,serialgc will test if average space when minor gc from eden promotion to old > old gen free space, if true,thenfull,iffalse,then base on HandleProtomotionFailure value.
  • 19. Minor GC—Serial public class SerialGCDemo{ public static void main(String[] args) throws Exception{ byte[] bytes=new byte[1024*1024*2]; byte[] bytes2=new byte[1024*1024*2]; byte[] bytes3=new byte[1024*1024*2]; System.out.println("step 1"); bytes=null; byte[] bytes4=new byte[1024*1024*2]; Thread.sleep(3000); System.out.println("step 2"); byte[] bytes5=new byte[1024*1024*2]; byte[] bytes6=new byte[1024*1024*2]; bytes4=null; bytes5=null; bytes6=null; System.out.println("step 3"); byte[] bytes7=new byte[1024*1024*2]; Thread.sleep(3000); } } -Xms20M –Xmx20M –Xmn10M –XX:+UseSerialGC -Xms20M –Xmx20M –Xmn10M -XX:-HandlePromotionFailure –XX:+UseSerialGC
  • 20. Minor GC—Serial The example execute different when use two type args,because this rule: when minor gc occurs: average space when minor gc from eden promotion to old < old gen free space < eden+from capacity if HandlePromotionFailure=true,then minor gcoccurs,iffalse,then full gc occurs.
  • 21. Minor GC—Serial The rule for new gen promotion to old gen. 1. the object still alive after some times minor gc; based on MaxTenuringThreshold,default value is 15. 2. to space is not enough,then direct to old.
  • 22. Minor GC—Serial public class SerialGCThreshold{ public static void main(String[] args) throws Exception{ SerialGCMemoryObject object1=new SerialGCMemoryObject(1); SerialGCMemoryObject object2=new SerialGCMemoryObject(8); SerialGCMemoryObject object3=new SerialGCMemoryObject(8); SerialGCMemoryObject object4=new SerialGCMemoryObject(8); object2=null; object3=null; SerialGCMemoryObject object5=new SerialGCMemoryObject(8); Thread.sleep(4000); object2=new SerialGCMemoryObject(8); object3=new SerialGCMemoryObject(8); object2=null; object3=null; object5=null; SerialGCMemoryObject object6=new SerialGCMemoryObject(8); Thread.sleep(5000); } } class SerialGCMemoryObject{ private byte[] bytes=null; public SerialGCMemoryObject(int multi){ bytes=new byte[1024*256*multi]; } } -Xms20M –Xmx20M –Xmn10M –XX:+UseSerialGC -Xms20M –Xmx20M –Xmn10M –XX:+UseSerialGC -XX:MaxTenuringThreshold=1
  • 23. Minor GC—Serial change the object1 code: SerialGCMemoryObject object1=new SerialGCMemoryObject(2); -Xms20M –Xmx20M –Xmn10M –XX:+UseSerialGC
  • 24. Minor GC—Serial The example shows object1 direct to oldwhen the second minor gc occurs, because this rule: after minor gc, then TenuringThreshold will be recaculted. (the first time TenuringThreshold= MaxTenuringThreshold) caculate rule: sum the bytes in per age,when the sum value > to space half,minor(age, MaxTenuringThreshold) can use PrintTenuringDistribution to see TenuringThreshold: Desired survivor size 524288 bytes, new threshold 1 (max 15). so MaxTenuringThreshold only represents max tenuringthreshold.
  • 25. Minor GC—Serial [GC [DefNew: 11509K->1138K(14336K), 0.0110060 secs] 11509K->1138K(38912K), 0.0112610 secs] [Times: user=0.00 sys=0.01, real=0.01 secs]
  • 26. Minor GC—ParNew when use cmsgc,this is default,also can use -XX:+UseParNewGC to use; 2. eden/s0/s1 capacity controlled by -XX:SurvivorRatio,the default value is 8,meaning eden:s0. ParNew memory allocation and gc is same as Serial,only difference is ParNew use multi threads to gc,but if add -XX:+UseAdaptiveSizePolicy,then many differences.
  • 27. Minor GC—ParNew [GC [ParNew: 11509K->1152K(14336K), 0.0129150 secs] 11509K->1152K(38912K), 0.0131890 secs] [Times: user=0.05 sys=0.02, real=0.02 secs] if add -XX:+UseAdaptiveSizePolicy to startup args,then output: [GC [ASParNew: 7495K->120K(9216K), 0.0403410 secs] 7495K->7294K(19456K), 0.0406480 secs] [Times: user=0.06 sys=0.15, real=0.04 secs]
  • 28. Minor GC—PS server class machine default,also can add -XX:+UseParallelGC to use; eden/s0/s1 capacity can be controlled by InitialSurvivorRatioor SurvivorRatio,when no above two args,then use InitialSurvivorRatio,the default value is 8,but its meaning isnew gen:survivor.
  • 29. Minor GC—PS mostly allocate on TLAB or eden. public class PSGCDemo{ public static void main(String[] args) throws Exception{ byte[] bytes=new byte[1024*1024*2]; byte[] bytes2=new byte[1024*1024*2]; byte[] bytes3=new byte[1024*1024*2]; Thread.sleep(3000); byte[] bytes4=new byte[1024*1024*4]; Thread.sleep(3000); } } -Xms20M –Xmx20M –Xmn10M –XX:SurvivorRatio=8 –XX:+UseParallelGC
  • 30. Minor GC—PS The example shows bytes4 object allocate on old gen, because this rule: when allocate fail on TLAB、eden,test if allocate space>= half of eden space,iftrue,then allocate on old gen.
  • 31. Minor GC—PS when eden space is not enough,and not allocate on old,thengc occurs. public class PSGCDemo{ public static void main(String[] args) throws Exception{ byte[] bytes=new byte[1024*1024*2]; byte[] bytes2=new byte[1024*1024*2]; byte[] bytes3=new byte[1024*1024*2]; System.out.println(“step 1"); byte[] bytes4=new byte[1024*1024*2]; Thread.sleep(3000); System.out.println(“step 2"); byte[] bytes5=new byte[1024*1024*2]; byte[] bytes6=new byte[1024*1024*2]; System.out.println(“step 3"); byte[] bytes7=new byte[1024*1024*2]; Thread.sleep(3000); } } -Xms20M –Xmx20M –Xmn10M –XX:SurvivorRatio=8 –XX:+UseParallelGC -XX:+PrintGCDetails –XX:verbose:gc
  • 32. Minor GC—PS the example shows one minor gc and two full gc,because this rule: 1. before gc,serialgc will test if average space when minor gcfrom eden promotion to old > old gen free space, if true,thenfull; 2. after gc,also do above test.
  • 33. Minor GC—PS The rule for new gen promotion to old gen. 1. the object still alive after some times minor gc: AlwaysTenure, the default value is false,meaning the alive objects will be promoted to old when minor gc. NeverTenure, the default value isfalse,meaning the alive objectswill never be promoted to old,except the to space is not enough. if the above two args are false and UseAdaptiveSizePolicy,then the first time based onInitialTenuringThreshold,but will be adjusted after every minor gc,if not UseAdaptiveSizePolicy,then based onMaxTenuringThreshold. 2. to space is not enough,then direct to old gen.
  • 34. Minor GC—PS After minor gc,ifUseAdaptiveSizePolicy,it’ll adjust eden space and to space based on runtime data,if don’t want to be adjusted,then add -XX:-UseAdaptiveSizePolicyto startup args.
  • 35. Minor GC—PS [GC [PSYoungGen: 11509K->1184K(14336K)] 11509K->1184K(38912K), 0.0113360 secs] [Times: user=0.03 sys=0.01, real=0.01 secs]
  • 36. Major GC Serial MSC Parallel MSC CMS Parallel Compacting which one should I choose?
  • 37. Major GC—Serial client class machine default,also can add -XX:+UseSerialGC to startup args to use.
  • 38. Major GC—Serial when occurs 1. old genis not enough; 2. perm gen is not enough; 3. the pessimistic rule when minor gc; 4. heap dump; 5. the code call System.gc,can use -XX:+DisableExplicitGC to disable.
  • 39. Major GC—Serial [Full GC [Tenured: 9216K->4210K(10240K), 0.0066570 secs] 16584K->4210K(19456K), [Perm : 1692K->1692K(16384K)], 0.0067070 secs] [Times: user=0.00 sys=0.00, real=0.01 secs]
  • 40. Major GC—Parallel MSC 1. server class machine default,also can add -XX:+UseParallelGC to use; 2. parallel threads cpu core<=8 ? cpu core : 3+(cpu core*5)/8 or use -XX:ParallelGCThreads=x to set.
  • 41. Major GC—Parallel MSC occur rule is same as Serial. note: if ScavengeBeforeFullGCis true(the default value), then execute minor GCfirst.
  • 42. Major GC—Parallel MSC [Full GC [PSYoungGen: 1208K->0K(8960K)] [PSOldGen: 6144K->7282K(10240K)] 7352K->7282K(19200K) [PSPermGen: 1686K->1686K(16384K)], 0.0165880 secs] [Times: user=0.01 sys=0.01, real=0.02 secs]
  • 43. Major GC—Parallel Compacting 1. can add -XX:+UseParallelOldGCto use; 2. parallel threads: cpu core<=8 ? cpu core : 3+(cpu core*5)/8 or use -XX:ParallelGCThreads=xto set.
  • 44. Major GC—Parallel Compacting occur rule is same as Parallel MSC.
  • 45. Major GC—Parallel Compacting [Full GC [PSYoungGen: 1224K->0K(8960K)] [ParOldGen: 6144K->7282K(10240K)] 7368K->7282K(19200K) [PSPermGen: 1686K->1685K(16384K)], 0.0223510 secs] [Times: user=0.02 sys=0.06, real=0.03 secs]
  • 46. Major GC—CMS 1. can add -XX:+UseConcMarkSweepGC to use; 2. mostly concurrent; 3. concurrent threads: (parallel gc threads +3)/4 or use–XX:ParallelCMSThreads=X to set.
  • 47. Major GC—CMS occur rule 1. when old gen used reach a percentage; default is 92%,can add PrintCMSInitiationStatistics(cann’t use in 1.5)to see default value,the default value caculate rule: ((100 - MinHeapFreeRatio) +(double)(CMSTriggerRatio * MinHeapFreeRatio) / 100.0)/ 100.0;MinHeapFreeRatiodefault value: 40 CMSTriggerRatiodefault value: 80 or use CMSInitiatingOccupancyFraction to set; 2. when perm gen used reach a percentage; perm gen use cms need to add: -XX:+CMSClassUnloadingEnabled default is 92%,default value caculate rule: ((100 - MinHeapFreeRatio) +(double)(CMSTriggerPermRatio* MinHeapFreeRatio) / 100.0)/ 100.0; MinHeapFreeRatiodefault value:40 CMSTriggerPermRatiodefault value: 80 or use CMSInitiatingPermOccupancyFractionto set;
  • 48. Major GC—CMS occur rule 3. Hotspot decide when to executeCMS GCbased on runtime data; or to use -XX:+UseCMSInitiatingOccupancyOnly to disable this rule; 4. the code call System.gc when set ExplicitGCInvokesConcurrentto true; note: when use this and NIO,maybe occur the bug.
  • 49. Major GC—CMS public class CMSGCOccur{ public static void main(String[] args) throws Exception{ byte[] bytes=new byte[1024*1024*2]; byte[] bytes1=new byte[1024*1024*2]; byte[] bytes2=new byte[1024*1024*2]; byte[] bytes3=new byte[1024*1024*1]; byte[] bytes4=new byte[1024*1024*2]; Thread.sleep(5000); } } -Xms20M –Xmx20M –Xmn10M -XX:+UseConcMarkSweepGC -XX:+UseCMSInitiatingOccupancyOnly -XX:+PrintGCDetails -Xms20M –Xmx20M –Xmn10M -XX:+UseConcMarkSweepGC -XX:+PrintGCDetails
  • 50. Major GC—CMS 1. Promotion Failed when minor gc,to spaceis not enough,then promotion to old,but old is not enough too,then promotion failed;solution: increase to space,increase old space, or decrease cmsgc occur percentage. 2. Concurrent mode failure when need allocate on old,butcmsgc is running,then concurrent mode failure,and to keep safe,hotspot will execute serial full gc;solution:increase old space, or decrease cmsgc occur percentage.
  • 51. Major GC—CMS [GC [1 CMS-initial-mark: 13433K(20480K)] 14465K(29696K), 0.0001830 secs] [Times: user=0.00 sys=0.00, real=0.00 secs] [CMS-concurrent-mark: 0.004/0.004 secs] [Times: user=0.01 sys=0.00, real=0.01 secs] [CMS-concurrent-preclean: 0.000/0.000 secs] [Times: user=0.00 sys=0.00, real=0.00 secs] CMS: abort preclean due to time [CMS-concurrent-abortable-preclean: 0.007/5.042 secs] [Times: user=0.00 sys=0.00, real=5.04 secs] [GC[YG occupancy: 3300 K (9216 K)][Rescan (parallel) , 0.0002740 secs] [weak refs processing, 0.0000090 secs] [1 CMS-remark: 13433K(20480K)] 16734K(29696K), 0.0003710 secs] [Times: user=0.00 sys=0.00, real=0.00 secs] [CMS-concurrent-sweep: 0.000/0.000 secs] [Times: user=0.00 sys=0.00, real=0.00 secs] [CMS-concurrent-reset: 0.000/0.000 secs] [Times: user=0.00 sys=0.00, real=0.00 secs] when add -XX:+UseAdaptiveSizePolicy,then output CMS will change to ASCMS CMS GC Log
  • 54.
  • 56. We’ll learn gc can be used in jdk 1.6 how to use these gc what difference between these gc when gc will be executed how to solve oom how to monitor gc how to tuning gc how to realiazegc √ √ question: how to let minor gc use psgc,and major gc use parallel compacting gc? √ question:what is difference between psgcand parnewgc? √ question: pls write a code,when it execute first occur 5 minor gc,and 2 full gc,and 2 minor gc,finally 1 full gc.
  • 57. Let’s solve some OOM Case
  • 58. OOM Cases 1、java -Xms20m -Xmx20m -Xmn10m -XX:+UseParallelGC com. bluedavy.oom.JavaHeapSpaceCase1 2、java -Xms20m -Xmx20m -Xmn10m -XX:+HeapDumpOnOutOfMemoryError com.bluedavy.oom.JavaHeapSpaceCase2 3、execute com.bluedavy.oom.JavaHeapSpaceCase3 4、 execute com.bluedavy.oom.JavaHeapSpaceCase4 5、java -Xms1536m -Xmx1536m -Xss100m com.bluedavy.oom.CannotCreateThreadCase
  • 59. OOMtype the above examples show: 1、java.lang.OutOfMemoryError: GC overhead limit exceeded 2、java.lang.OutOfMemoryError: Java heap space 3、java.lang.OutOfMemoryError: unable to create new native thread and also belows: 4、java.lang.OutOfMemoryError: request bytes for . Out of swap space? two reason: memory is not enough; address space exhausted(for example on 32 bit linux the process can only use 3G address space) this OOMwill cause Java process exit; monitor who use native memory: google-perftools 5、java.lang.OutOfMemoryError: PermGen space PermGenis not enough;
  • 60. OOMsolution Java Heap SpaceOOM: 1. add -XX:+HeapDumpOnOutOfMemoryError; 2. jmap–histo; 3. jmap –dump; 4. hand to solve; 5. heap too small? Out of swap: 1. heap too large? 2. Google perftools,if not help,then no way... unable to create new native thread: 1. too many threads; 2. –Xss; PermGen space: 1. PermGentoo small? 2. too many ClassLoaders?
  • 61. OOM Reference 1. Sun JDK 6 troubleshooting Guide; 2.OOM
  • 62. GCMonitor 1. jstat–gcutil [pid] [intervel] [count] 2. -verbose:gc -XX:+PrintGCDetails -XX:+PrintGCApplicationStoppedTime -XX:+PrintGCDateStamps -XX:+PrintHeapAtGC -Xloggc:[file] gclog can be analised by GCLogVieweror gchisto. 3. if support GUI,then can use visualvm.
  • 63. who consume the memory 1. alive long situation,easy,jmap –dump,then MAT; 2. alive short,if no GUI,thenin trouble,ifGUI,thenjprofiler/visualvm.
  • 64. We’ll learn gc can be used in jdk 1.6 how to use these gc what difference between these gc when gc will be executed how to solve oom how to monitor gc how to tuning gc how to realiazegc √ √ √ √ √ java.lang.OutOfMemoryError: Java Heap Space,what can we do? √ pls tell me how many minor gc and full gc the app executes.
  • 65. tuning case 4 cpu,os: linux 2.6.18 32 bit startup args -server -Xms1536m -Xmx1536m –Xmn700m gc log: 67919.817: [GC [PSYoungGen: 588706K->70592K(616832K)] 1408209K->906379K(1472896K), 0.0197090 secs] [Times: user=0.06 sys=0.00, real=0.02 secs] 67919.837: [Full GC [PSYoungGen: 70592K->0K(616832K)] [PSOldGen: 835787K->375316K(856064K)] 906379K->375316K(1472896K) [PSPermGen: 64826K->64826K(98304K)], 0.5478600 secs] [Times: user=0.55 sys=0.00, real=0.55 secs]
  • 66. tuning case minor gc info
  • 67. tuning case gc log: 68132.862: [GC [PSYoungGen: 594736K->63715K(609920K)] 1401225K->891090K(1465984K), 0.0309810 secs] [Times: user=0.06 sys=0.01, real=0.04 secs] 68132.893: [Full GC [PSYoungGen: 63715K->0K(609920K)] [PSOldGen: 827375K->368026K(856064K)] 891090K->368026K(1465984K) [PSPermGen: 64869K->64690K(98304K)], 0.5341070 secs] [Times: user=0.53 sys=0.00, real=0.53 secs] then repeat.
  • 68. tuning case Goal decrease full gc frequency and pause time caused by gc. Method decrease response time or requests,difficult; decrease memory used per request,difficult; decrease memory promoted to old every minor gc,it’s ok;
  • 69. tuning case decrease memory promoted to old every minor gc increase new gen space,now new gen space is big,soit does not work; increase survivor space,it maybe works.
  • 70. tuning case increase Survivor space now PS GC,so survivor space is adjusted,but monitor this case,we can see mostly survivor space only have 1—4MB,it’s too small; so add -XX:-UseAdaptiveSizePolicy; caculate survivor spaceneed size see current to space size,and after minor gc,old gen increased size,then to space+old gen increased size will be survivor space need size; sum many times then average; adjust survivor space to desired size; after the adjustion,minorgcmore,but full gc decrease to every two hours.
  • 71. tuning case the method decrease full gcfrequency,but the pause time caused by gc only decrease 10%; keep Survivorspace,and use cms,the final startup args: -Xms1536m -Xmx1536m -Xmn700m -XX:SurvivorRatio=7 -XX:+UseConcMarkSweepGC-XX:CMSMaxAbortablePrecleanTime=1000 -XX:+CMSClassUnloadingEnabled-XX:+DisableExplicitGC
  • 73. GC Tuning—common policy decrease full gc frequency–common problem oldgen used too high;common reason: cache too many objects;for example: preparedstatement cacheset too big when use oracle driver;solution: dump then mat,bingo!
  • 74. GC Tuning—common policy decrease full gc frequency–common problem many objects promotion to old gen;common reason: survivor spacetoo small; response time is too slow; many memory used by per request;solution: decrease minor gc frequency; let object collect when minor gc,such as increase suvivorspace,new gen; use cmsgc;tuning application;
  • 75. GC Tuning—common policy decrease full gc time common reason:old gen is too big;solution: parallel gc?decrease heap or old gen; add cpu or upgrade cpu.
  • 76. GC Tuning—common policy decrease minor gc frequency common reasonminor gc too small; many memory used by per request;solutionincrease heap,new or eden; decrease memory used by per request.
  • 77. GC Tuning—common policy decrease minor gc time common reason response time too slowwsolutionadd cpu or upgrade cpu; if u use cmsgc,then as much as possible avoid object allocate or promote to old gen,or change to psgc.
  • 78. GC Tuning GC Tuning is art! The final solution is decrease response time or memory used per request; or upgrade to 64 bit,then use large heap,of course it needs more cpu.
  • 79. We’ll learn gc can be used in jdk 1.6 how to use these gc what difference between these gc when gc will be executed how to solve oom how to monitor gc how to tuning gc how to realiazegc √ √ √ √ √ √ √
  • 80. Garbage Collection 1. usually use below two methods:1.1 Reference counter not suitable for complex object reference situations; count will decrease performance; good point is when counters decrease to zero,then collect. 1.2 Tracing hotspot use; need pause the application. common algithorm: Copying/Mark-Sweep/Mark-Compact
  • 81. Garbage Collection Hotspot scan objects from root set; root set 1. current running thread; 2. public or static variables; 3. JVM Handles; 4. JNIHandles;
  • 82. Garbage Collection how to pause thread?safepointfirst: test a memory page readable; keypoint:only the code will cause the reference change need pause; so when gcoccurs,it’ll submit a request to core,then core set the memory page cannot read,when code execute reach safepoint,then pause.
  • 83. Minor GC Serial Parallel Scavenge ParNew
  • 84. Minor GC allocate on a continous space and use bump the pointer. A B C D
  • 85. Minor GC the policy: scan new gen objects, find alive objects; use copying algorithm to finish collection.
  • 86. Minor GC because minor gc only scan new gen,if old gen references new gen,how to do?when assign a reference value,will pass a write barrier;test if old gen ref new gen object,iftrue,then record to remember set;when minor gc,the objects in remember set also put into root set.
  • 87. Major GC Serial MSC Parallel MSC CMS Parallel Compacting
  • 88. Major GC—Serial Memory allocation policy 1. not support TLAB; 2. bump pointer.
  • 89. Major GC—Serial Garbage Collection Policy based on Mark Sweep Compact algorithm. split four phases: 1. mark which object alive; 2. caculate new address; 3. update pointer to new address; 4. move object to new address.
  • 90. Major GC—Parallel MSC Memory allocation policy bump pointer.
  • 91. Major GC—Parallel MSC The only difference with serial is multi threads.
  • 92. Major GC—Parallel Compacting Memory allocation is same as parallel MSC.
  • 93. Major GC—Parallel Compacting Garbage Collection policy:
  • 94. Major GC—CMS Memory Allocation Policy 1. first get freelist lock; 2. find which chunk can put the object; 3. if now gc in marking phase,the mark the object alive.
  • 95. Major GC—CMS start a cms thread first; based on Mark-Sweep,split into five phase; Initial Marking(Stop-the-world)Concurrent MarkingPreClean(Sun jdk 1.5 added)Final Marking(Stop-the-world) Concurrent Sweeping
  • 96. Major GC—CMS Initial Marking (Stop-the-world)markroot setdirect ref objects; Concurrent Markingconcurrent mark phase 1 marked objects recursively; Mod Union Tableto solve the ref change when minor gc executes; Card Table to solve the ref change in the old gen.
  • 97. Major GC—CMS Preclean scan again phase 2 marked objects and dirty objects;-XX: CMSScheduleRemarkEdenSizeThreshold、-XX: CMSScheduleRemarkEdenPenetration this step maybe causes bug,when object need allocate old, but remark phase not execute,then old space not enough, so current step have a timeout arg,default value is 5000ms, or use -XX: CMSMaxAbortablePrecleanTime to control.
  • 98. Major GC—CMS Final Marking (Stop-the-world)scan Mod Union Table/Card Table,then remark. Concurrent Sweepingcollect the memory used by “dead” objects.
  • 99. Major GC—CMS good point and weak point; mostly concurrent,so it’ll only pause application little time; float garbage,so need more memory size; memory fragment; fight for cpu,so it not suit for cpu intensive app; multi mark,sogc time is longer then parallel gc; memory allocation need use free list,soit’s slower then bumppointer allocate; concurrent with application,so free list will compete.
  • 101. Study SUN JDK V1.6 GC sources download JDK sources; use Source Insightetc. tools to see SerialGC、ParNewGC GenCollectedHeap::mem_allocate PS GC ParallelScavengeHeap::mem_allocate CMS GC ConcurrentMarkSweepThread::run CMSCollector::collect
  • 102. We’ll learn gc can be used in jdk 1.6 how to use these gc what difference between these gc when gc will be executed how to solve oom how to monitor gc how to tuning gc how to realiazegc √ √ √ √ √ √ √ √
  • 103. References 1. GC Tuning in the Hotspot 2. Our Collectors 3. CMS GC 4. why now 5. hotspot 6.0 gc tuning 6. memory management in hotspot whitepaper