Java Virtual machine memory and garbage collection summary __java

Source: Internet
Author: User
Tags xms
1. Runtime Memory Partitioning 1.1. Program CounterThe bytecode line number indicator, which is used to read the next byte code instruction that needs to be executed. Log the virtual machine bytecode instruction address to the Java method; null for the native method record value. Threads are private and each thread does not affect each other. 1.2. Virtual Machine StackJava method is created by the execution of a method, each call to create a stack frame and put it into the stack, the method is completed after the stack frame stack. The stack frame holds the local variable table (compile period assignment, including basic data type, object reference), operand stack, dynamic link, method exit. Threads are private and each thread does not affect each other. Two exceptions can be thrown: stackoverflowerror (the requested stack depth is too large) and outofmemoryerror (dynamic expansion cannot request enough memory). 1.3. Local method StackThe native method is created in the same way as the virtual machine stack. The Sun hotspot virtual machine merges the virtual machine stack with the local method stack. 1.4. Java HeapThe largest chunk of memory, used to hold object instances and arrays, and areas where the garbage collector is primarily administered. The virtual machine is created when it is started, all threads are shared, but there is a thread-private allocation buffer. You can throw an exception outofmemoryerror (dynamic expansion cannot apply to enough memory).
Cenozoic 1/3⎧⎩⎨⎪⎪edenfrom Survivorto Survivor8/101/101/102/3 Heap \left\{\begin{array}{ll of new generation &1/3\left\{\ in the old era of heap ⎧⎩⎨⎪⎪⎪⎪ BEGIN{ARRAY}{LL} eden&8/10\\ from\ survivor&1/10\\ to\ survivor&1/10\\ \end{array}\right.\\ old age &2/3 \ End{array}\right. 1.5. Method AreaStore class information, run a regular pool, static variables, just-in-time code, etc., the Sun hotspot virtual machine with the permanent generation of the implementation of the method area. Garbage collection is infrequent, with only constant pools and type unload targets. class file constant pool the literal amount of the compilation period (string variable, final constant), and symbol reference (class name, member variable name, method name), in which the class loads the LIFO runtime pool. shared by all threads. You can throw an exception outofmemoryerror (dynamic expansion cannot apply to enough memory).

In addition: Direct memory
It is not part of run-time memory, it is the use of the native method allocated by the NIO class in the outer heap of memory, on the heap has Directbytebuffer objects referencing direct memory, you can avoid the Java heap and the native heap back and forth replication.
is not limited by the Java heap size, but can throw an exception outofmemoryerror.2. Memory Overflow Exception 2.1. Java Heap Overflowobject instance reaches maximum heap capacity limit, resulting in java.lang.OutOfMemoryError:Java heap space anomaly. Resolution Policy: If it is a memory leak, analyze the leak object to the GC roots reference Path, find out why the garbage collector is not automatically recycled, or if it is a memory overflow, the virtual machine memory parameter allocation is too small, or some objects in the code have a long lifecycle. JVM Related parameters:-xms,-xmx2.2. Virtual machine stack and local method stack OverflowThe stack depth requested by one thread is too large to produce a Java.lang.StackOverflowError exception. Creating too many threads, the stack allocated for the thread causes insufficient memory to produce the java.lang.OutOfMemoryError:unable to create new native thread exception. JVM Related parameters:-XSS2.3. Method area and run frequent pool overflowThe runtime is a part of the method area, implemented by a permanent generation. If you compile too many literal amounts or generate a large number of class classes (reflection), you can cause a Java.lang.OutOfMemoryError:PermGen space exception to run from a constant pool. The String.intern () method can be used to run a constant pool at the time the program runs, when a string equal to the string object is already stored in the Run-time pool, and the reference in the running constant pool is returned, otherwise the string of that string object is added to the running constant pool. Returns a reference to the string for the string object. If you constantly create different strings and call the String.intern () method, it overflows. JVM Related parameters:-xx:permsize,-xx:maxpermsize2.4. Direct Memory OverflowUsing reflection to obtain an instance of unsafe, and unsafe.allocatememory () a large number of memory allocation, resulting in Java.lang.OutOfMemoryError exception. JVM Related parameters:-xx:maxdirectmemorysize (Default and-XMX)3. Garbage collection 3.1. Memory that needs to be recycled

program counters, virtual machine stacks, and local method stacks are born with threads and do not need to be recycled. The Java heap and method extents know at run time which memory needs to be allocated and need to be recycled. 3.1.1. Reference counting method (JVM not used)

Adds a reference counter to an object that, whenever it is referenced by a place, adds 1 to the counter value, minus 1 when the reference is invalidated, and any time the object with a counter of 0 is impossible to recycle. The disadvantage is that the circular reference problem cannot be resolved. 3.1.2. Accessibility analysis (JVM use)

From the root (GC Roots) object as the starting point, start the downward search, the search path is referred to as "reference chain", when an object to the GC Roots no reference chain is connected, it is proved that this object is not available need to recycle.
objects that can be used as GC roots are objects that are referenced by the virtual machine stack (the local variable table in the stack frame) in the static object method area of the object method region in a const object (in a constant pool) in the local method stack (native method) 3.1.3. Reference classification strong references: ubiquitous, the garbage collector will never recycle, even if the program terminates the soft reference (SoftReference Class): If the memory is sufficient, it will not be recycled, memory is not enough and before the overflow, the objects will be reclaimed two times, if the memory is still insufficient to throw an exception. Memory-sensitive cache weak reference (WeakReference Class): Can only survive until the next garbage collection, by which time the virtual reference (Phantomreference Class) will be recycled, regardless of the memory: the object instance cannot be obtained without any references, Can be reclaimed at any time, tracking only the activities that the object is reclaimed 3.1.4. Method Zone Recycle

Mainly for discarded constants and useless classes, but not necessarily need to recycle, because the method area (permanent generation) recycling efficiency is much lower than the Java heap. 3.2. The timing and manner of garbage collection 3.2.1. Mark-The Purge algorithm marks (through the root node, all unreachable objects starting from the root node), and then clears (the object that is marked for collection). Disadvantages: Marking and purging require a low traversal efficiency, and a large number of discontinuous fragments are generated when the mark is cleared. 3.2.2. The replication algorithm (Cenozoic) divides the original memory space into equal two blocks, uses only one piece at a time, and when there is not enough memory, copies the surviving object into the unused memory block, and then clears all the objects in the memory block that is being used. Suitable for the low survival rate of the object, corresponding to the Cenozoic minor GC. Advantages: No memory fragmentation, allocating memory sequentially is simple and efficient. Disadvantage: space waste. Improvement: Divide the memory into three pieces, a large Eden (8/10) and two small survivor (1/10), each using Eden and one of the survivor, and preferentially distributed in Eden. Recycle the surviving objects in Eden and survivor to another piece of survivor, and finally clean up the used Eden and survivor. When the survivor is not enough, it is necessary to rely on the old age for distribution guarantees, so that large objects directly into the old age. 3.2.3. Mark-The collation algorithm (old age) marks (through the root node, all the accessible objects starting from the root node), and then collates (all the accessible objects move to one end of the memory and clean out the outer memory). Applies to the case of high survival of the object, corresponding to the full GC in the old age. Benefits: no memory fragmentation. Disadvantage: The marking movement efficiency is not high.

Comparison of three methods
Efficiency: Copy algorithm > tag-collation algorithm > tag-purge algorithm.
Memory uniformity: Replication algorithm = tag-collation algorithm > tag-purge algorithm.
Memory utilization: Tag-collation algorithm = tag-purge algorithm > Replication algorithm.4. Garbage collector 4.1. Serial collectorA single-threaded replication algorithm collector that must suspend all other worker threads (Stop-the-world) for garbage collection. Application: Default in Client modeCenozoicCollector. Advantages: There is no thread interaction overhead, with the highest single thread collection efficiency.4.2. Parnew CollectorMulti-threaded replication algorithm collector, the rest is similar to the serial collector. Application: Preferred in server modeCenozoicCollector. Advantages: Single-thread collection efficiency is not high, but can take advantage of multiple CPU resources.4.3. Parallel scavenge collectorA multi-threaded replication algorithm collector, similar to the Parnew collector, but can control CPU throughput (user code time/total time) and increase CPU utilization. Application: Suitable for background operation does not require too much interactionCenozoicCollector. Advantages: You can increase throughput, but may increase the pause time. Because of the increased throughput, the frequency of the GC decreases, and each GC pause increases. Can be adaptive to dynamically adjust throughput and pause time.4.4. Serial Old collectorSingle-threaded tagging-sorting algorithm collectors, which can be used with a variety of new generation collocation old age collectors. Application: Default in Client modeold ageCollector, an alternative to the CMS collector in server mode.4.5. Parallel Old collectorMulti-threaded tag-collation algorithm collector. Application: can match with parallel scavenge collectorold ageCollector. Benefits: You can leverage multiple CPU resources.4.6. CMS collectorA multithreaded tag-cleanup algorithm collector. Includes 4 steps: initial tag, concurrent tag, re-tagging, concurrency cleanup. Concurrent markup and concurrent cleanup operations can work with user threads. Application: Can get the shortest recovery timeold ageCollector. Disadvantages: 1. The concurrency phase consumes threads and reduces throughput by 2. Inability to process floating garbage (user program's new garbage) will cause the collection to fail, thereby using the saerial old collector to collect again; 3. Mark-Cleanup produces memory fragmentation and collation is not concurrent.4.7. G1 CollectorCan independently manage the new generation and old age collectors. Advantages: 1. Concurrent collection reduces pauses; 2. Generational collection; 3. Integration of the tag-collation and replication algorithm, there will be no memory fragmentation; 4. Predictable pause time.5. JVM Parameters

defaults
-xms initial heap size physical memory 1/64
-X MX max heap size physical memory 1/4
-xmn cenozoic size heap 3/8
-xx:newsize set Cenozoic size
-xx:maxnewsize Cenozoic Maximum
-xx:permsize Set permanent generation initial value physical memory 1/64
-xx:maxpermsize Set the maximum value for permanent generation physical memory 1/4
-xss per thread stack size Small application 128k large enough to apply recommended 256k
-xx:newratio ratio of old age to Cenozoic (excluding permanent generation)
-xx:survivorratio eden survivor ratio

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.