Java heap memory

Source: Internet
Author: User
Tags xms

Java heap memory

?? The heap in Java is the largest memory space managed by JVM. It is mainly used to store various types of instance objects.
?? In Java, the heap is divided into two different regions: Young and Old ). The Young generation is divided into three regions: Eden, From nation vor, And To nation vor.
?? This Division aims to enable JVM to better manage objects in heap memory, including memory allocation and collection.
?? The heap memory model is roughly as follows:

?? Young Generation: Young Generation, mainly used to store new objects.
?? Old: Old Generation, or Tenured Generation, mainly stores memory objects with long application declaration cycles.

Permanent generation: (The method area does not belong to the java Heap. The other alias is "Non-Heap", but generally PrintGCDetails will carry the PermGen area) refers to the permanent storage area of the memory, it stores information about the Class and Meta. When the Class is loaded, it is placed in the PermGen space area. unlike the Heap region where the Instance is stored, GC (Garbage Collection) does not clean up PermGen space during the main program running, so if your application loads many classes, the PermGen space error may occur.

?? Heap size = new generation + old generation. The heap size can be specified by the-Xms and-Xmx parameters.
?? By default, the ratio of Young to Old is (this value can be specified by the-XX: NewRatio parameter), that is, Young) = The heap size of 1/3. Old age (Old) = 2/3 heap space. Among them, the new generation (Young) is subdivided into Eden and two region vor regions. The two region vor regions are named from and to respectively to distinguish them.
?? The default value is Edem: from: to = 8: 1: 1 (you can set it by the-XX: SurvivorRatio parameter), that is, Eden = the size of the new generation space of 8/10, from = to = the size of the new generation space of 1/10.
?? Each time the JVM uses Eden and one of the Region vor regions to serve the object, a region VOR is always idle at any time.
?? Therefore, the actual available memory space of the new generation is 9/10 (that is, 90%) of the new generation space.

Recycling Method Area (additional supplement)

??Many people think that there is no garbage collection in the Method Area (or permanent [PermGen] In the HotSpot Virtual Machine). the Java Virtual Machine specification does say that it does not require virtual machines to implement garbage collection in the method area, in addition, the "cost-effectiveness" of method-based garbage collection is generally relatively low.: In the heap, especially in the new generation, conventional applications can collect 70%-95% of the space for garbage collection at a time, and the permanent generation of garbage collection efficiency is far lower than this.
?? Permanent garbage collection mainly recycles two parts: obsolete constants and useless classes.
?? Obsolete constants: Recycling discarded constants is very similar to recycling objects in the java heap. Taking the collection of constants in the constant pool as an example, adding a String "abc" has already entered the constant pool, but no String object in the current system is called "abc". In other words, that is, there is any "abc" constant in the constant pool of the String object, and there is no reference to this literal in other places. If memory is recycled at this time and necessary, the "abc" constant will be cleared out of the constant pool by the system. Symbol references of other classes (interfaces), methods, and fields in the constant pool are similar.(Note: JDK and later versions have removed the constant pool from the permanent generation)
?? Useless class: the class must satisfy the following three conditions at the same time to be considered "useless class ":

All instances of this class have been recycled, that is, no instances of this class exist in the java heap. The ClassLoader for loading the Class has been recycled. the java. lang. Class Object corresponding to the Class is not referenced anywhere, and the method for accessing the Class through reflection is not allowed anywhere.

?? Virtual machines can recycle useless classes that meet the preceding three conditions. Here, we only say "yes", instead of being the same as an object. If it is not used, it will inevitably be recycled. Whether to recycle classes. The HotSpot virtual machine provides-Xnoclassgc (disable the CLASS garbage collection function, that is, the classes loaded by the Virtual Machine. Even if it is not used, no instances will be recycled .) Parameters.

In scenarios where reflection, dynamic proxy, CGlib, and other ByteCode frameworks are widely used, JSP is dynamically generated, and frequent custom ClassLoader such as OSGi is required, the virtual machine must have the class uninstall function, to ensure that the permanent generation will not overflow.

GC

?? The heap in Java is also the main area for GC to collect garbage. There are two types of GC: Minor GC and Full GC (or Major GC ).
?? Minor GC is a garbage collection action that occurs in the new generation. It adopts a replication algorithm.
?? The new generation is where almost all Java objects are born, that is, the memory applied for by Java objects and stored in this place. Most objects in Java usually do not need to survive for a long time and have the nature of extinction.
?? When an object is declared as "dead", GC has the responsibility to reclaim the memory space of this part of the object. The new generation is a frequent area where GC collects garbage.
?? When an object is born in Eden (including a region vor region, this is assumed to be from Region), after a Minor GC, if the object is still alive, and can be accommodated by another region vor region (the above is assumed as the from Region, Here it should be the to region, that is, the to region has enough memory space to store the objects in the Eden and from regions ), then, the replication algorithm is used to copy these surviving objects to another region (I .e. to region), and then the used Eden and region (I .e. from region) are cleared ), and set the age of these objects to 1. After a Minor GC occurs in the VOR region, the age of the object is + 1, when the age of an object reaches a certain value (the default value is 15 years old, it can be set through the-XX: MaxTenuringThreshold parameter), these objects will become old.
?? However, this is not certain. For some large objects (that is, a large continuous memory space needs to be allocated), it directly enters the old age. The virtual machine provides the-XX: PretenureSizeThreshold parameter, so that objects greater than the set value are directly allocated in the old age. The purpose of this operation is to avoid a large amount of memory replication between the Eden and two vor regions (the new generation uses the replication algorithm to collect memory ).
?? In order to better adapt to the memory conditions of different programs, the virtual machine does not always require that the object age must reach MaxTenuringThreshold to be promoted to the old age, if the total size of all objects of the same age in the primary vor space is greater than half of the primary vor space, objects of the same age or age can enter the old age without waiting for the age specified in MaxTenuringThreshold.
?? Full GC is a garbage collection action that occurs in the old age. It uses the "mark-clear" or "mark-clear" algorithms.
?? In real life, people in the old age often die earlier than the new generation ". In the heap memory, the Old age (Old) is different from this. In the Old age, almost all objects are in the same region as the Old ones. They are not so easy to "die. Therefore, Full GC occurs less frequently than Minor GC, and it takes longer to perform Full GC than to perform Minor GC.
?? Before the occurrence of MinorGC, the virtual opportunity first checks whether the maximum available continuous space in the old age is greater than the total space of all objects in the new generation. If this condition is true, MinorGC can ensure security. If this parameter is not set, you can check whether the HandlePromotionFailure value allows guarantee failure. If yes, check whether the maximum available continuous space in the old age is greater than the average size of objects promoted to the old age. If yes, try MinorGC, although this MinorGC is risky, if the value is smaller than or if the HandlePromptionFailure setting does not allow risk taking, it will also be changed to a FullGC.
?? In addition, when the tag-clearing algorithm collects garbage, it will generate a lot of memory fragments (that is, discontinuous memory space). When a large object needs to be allocated memory space, if sufficient continuous memory space cannot be found, GC collection is triggered in advance.

GC log

First, let's take a look at the following code:

package jvm;public class PrintGCDetails{    public static void main(String[] args)    {        Object obj = new Object();        System.gc();        System.out.println();        obj = new Object();        obj = new Object();        System.gc();        System.out.println();    }}

?? Set the JVM parameter to-XX: + PrintGCDetails. The execution result is as follows:

[GC [PSYoungGen: 1019 K-> 568 K (28672 K)] 1019 K-> 568 K (92672 K), 0.0529244 secs] [Times: user = 0.00 sys = 0.00, real = 0.06 secs] {User-Defined annotation of the blogger: [GC [New Generation: memory usage of the new generation before MinorGC-> memory usage of the new generation after MinorGC (total memory size of the New Generation)] minorGC: JVM heap memory usage-> MinorGC: JVM heap memory usage (available memory size of the heap), total time consumed by MinorGC] [Times: user time consumed = 0.00 system time consumed = 0.00, actual time consumed = 0.06 secs]} [Full GC [PSYoungGen: 568 K-> 0 K (28672 K)] [ParOldGen: 0 K-> 478 K (64000 K)] 568 K-> 478 K (92672 K) [PSPermGen: 2484 K-> 2483 K (21504 K)], 0.0178331 secs] [Times: user = 0.01 sys = 0.00, real = 0.02 secs] {blogger custom annotation: [Full GC [PSYoungGen: 568 K-> 0 K (28672 K)] [old age: memory usage in the old age before FullGC-> memory usage in the old age after FullGC (total memory size in the old age)] size of JVM heap memory before FullGC-> size of JVM heap memory after FullGC (available memory size of the heap) [permanent generation: 2484 K-> 2483 K (21504 K)], 0.0178331 secs] [Times: user = 0.01 sys = 0.00, real = 0.02 secs]} [GC [PSYoungGen: 501 K-> 64 K (28672 K)] 980 K-> 542 K (92672 K), 0.0005080 secs] [Times: user = 0.00 sys = 0.00, real = 0.00 secs] [Full GC [PSYoungGen: 64 K-> 0 K (28672 K)] [ParOldGen: 478 K-> 479 K (64000 K)] 542 K-> 479 K (92672 K) [PSPermGen: 2483 K-> 2483 K (21504 K)], 0.0133836 secs] [Times: user = 0.05 sys = 0.00, real = 0.01 secs] Heap PSYoungGen total 28672 K, used 1505 K [0x00000000e0a00000, 0x00000000e2980000, 0x0000000100000000) eden space 25088 K, 6% used [average, minimum, 0x00000000e2280000) from space 3584 K, 0% used [clerk, 0x00000000e2600000, 0x000000000000e2980000) to space 3584 K, 0% used [0x000000000000e2280000, 0x0000e2280000, clerk) ParOldGen total 64000 K, used 479 K [Clerk, california, California) object space 64000 K, 0% used [0x00000000a1e00000, California, California) PSPermGen total 21504 K, used 2492 K [0x0000000000009cc00000, 0x000000009e100000, 0x00000000a1e00000) object space 21504 K, 11% used [0x000000009cc00000, 0x0000000000009ce6f2d0, 0x000000009e100000)

Note: You can use JConsole or Runtime. getRuntime (). maxMemory (), Runtime. getRuntime (). totalMemory (), Runtime. getRuntime (). freeMemory () to view the size of heap memory in Java.

?? Let's look at another example:

Package jvm; public class PrintGCDetails2 {/***-Xms60m-Xmx60m-Xmn20m-XX: NewRatio = 2 (if Xms = Xmx and Xmn is set, * This configuration does not need to be configured.)-XX: Export vorratio = 8-XX: PermSize = 30 m-XX: MaxPermSize = 30 m *-XX: + PrintGCDetails */public static void main (String [] args) {new PrintGCDetails2 (). doTest ();} public void doTest () {Integer M = new Integer (1024*1024*1); // unit, MB (M) byte [] bytes = new byte [1 * M]; // apply for 1 M memory size bytes = null; // disconnect the reference chain System. gc (); // notify GC to collect garbage System. out. println (); bytes = new byte [1 * M]; // re-apply for 1 MB memory size bytes = new byte [1 * M]; // apply for 1 MB memory space again. gc (); System. out. println ();}}

?? Running result:

[GC [PSYoungGen: 2007K->568K(18432K)] 2007K->568K(59392K), 0.0059377 secs] [Times: user=0.02 sys=0.00, real=0.01 secs] [Full GC [PSYoungGen: 568K->0K(18432K)] [ParOldGen: 0K->479K(40960K)] 568K->479K(59392K) [PSPermGen: 2484K->2483K(30720K)], 0.0223249 secs] [Times: user=0.01 sys=0.00, real=0.02 secs] [GC [PSYoungGen: 3031K->1056K(18432K)] 3510K->1535K(59392K), 0.0140169 secs] [Times: user=0.05 sys=0.00, real=0.01 secs] [Full GC [PSYoungGen: 1056K->0K(18432K)] [ParOldGen: 479K->1503K(40960K)] 1535K->1503K(59392K) [PSPermGen: 2486K->2486K(30720K)], 0.0119497 secs] [Times: user=0.02 sys=0.00, real=0.01 secs] Heap PSYoungGen      total 18432K, used 163K [0x00000000fec00000, 0x0000000100000000, 0x0000000100000000)  eden space 16384K, 1% used [0x00000000fec00000,0x00000000fec28ff0,0x00000000ffc00000)  from space 2048K, 0% used [0x00000000ffe00000,0x00000000ffe00000,0x0000000100000000)  to   space 2048K, 0% used [0x00000000ffc00000,0x00000000ffc00000,0x00000000ffe00000) ParOldGen       total 40960K, used 1503K [0x00000000fc400000, 0x00000000fec00000, 0x00000000fec00000)  object space 40960K, 3% used [0x00000000fc400000,0x00000000fc577e10,0x00000000fec00000) PSPermGen       total 30720K, used 2493K [0x00000000fa600000, 0x00000000fc400000, 0x00000000fc400000)  object space 30720K, 8% used [0x00000000fa600000,0x00000000fa86f4f0,0x00000000fc400000)

?? The printed results show that the memory space of the New Generation in the heap is 18432 K (about 18 M), and the memory space of the eden is 16384 K (about 16 M ), from/to memory VOR has a memory size of 2048 KB (about 2 MB ).
?? The Xmn configured here is 20 M, that is, the memory space of the new generation is 20 M. But from the printed heap information, how can the new generation only have 18 M? Where is the other 2 M?
?? Don't worry, that's it. The new generation = eden + from + to = 16 + 2 + 2 = 20 M. It can be seen that the memory space of the new generation is indeed allocated by the Xmn parameter.
?? In addition, Region vorratio = 8 is specified here. Therefore, the new generation space of eden = 8/10 is 8/10*20 = 16 M. From = to = 1/10 of the New Generation Space = 1/10*20 = 2 M.
?? In the heap information, the total 18432 K of the new generation is like this: eden + 1 kernel vor = 16384 K + 2048 K = 18432 K, that is, about 18 M.
?? Because the jvm only uses the eden of the new generation and a dedicated vor each time, the actual available memory size of the new generation is 90%.
?? Therefore, we can know that the memory space of the New Generation refers to the total memory space available for the new generation, rather than the size of the new generation.
?? In addition, we can see that the memory space in the old age is 40960 K (about 40 M), and the heap size = new generation + old generation. So here, the old age = heap size-New Generation = 60-20 = 40 M.
?? Finally, PermSize = 30 m is also specified here, And PermGen is the permanent generation (Method Area). It also has a name called non-heap, it is mainly used to store information, constants, and static variables of class files loaded by jvm.

Appendix: Common JVM Parameters

-XX: +

Enable Option
-XX :- Disable Option
-XX: =
-XX: =

Heap settings
-Xms: initial heap size
-Xmx: Maximum heap size
-Xmn: New Generation size. Usually 1/3 or 1/4 of Xmx. New Generation = Eden + 2 shards vor space. The actual available space is = Eden + 1 dedicated vor, that is, 90%
-XX: NewSize = n: Set the young generation size
-XX: NewRatio = n: Ratio of the young generation to the old generation. For example, if the value is 3, the ratio of the young generation to the old generation is. The young generation accounts for 1/4 of the young generation and the old generation.
-XX: Ratio vorratio = n: Ratio of the Eden zone in the young generation to the two region vor zones. Note that there are two vor zones. For example, 3 indicates Eden: Primary vor =. One primary vor zone accounts for 1/5 of the young generation.
-XX: PermSize = the initial size of n permanent generation (Method Area)
-XX: MaxPermSize = n: sets the permanent generation size.
-Xss sets the stack capacity. For HotSpot, although the-Xoss parameter (set the local method stack size) exists, it is actually invalid, because in HotSpot, virtual machines and local method stacks are not distinguished.
-XX: PretenureSizeThreshold (this setting takes effect only for the Serial and ParNew collectors). You can set the size limit for entering the old generation.
-XX: MaxTenuringThreshold = 1 (15 by default) maximum age of spam. If it is set to 0, the young generation object directly enters the old generation without going through the same vor area. for applications with many older generations, the efficiency can be improved. if this value is set to a greater value, the young generation object will be copied multiple times in the same vor area, which can increase the survival time of the young generation object, increase the probability of being recycled in the young generation
This parameter is valid only for serial GC.
Collector settings
-XX: + UseSerialGC: sets the serial collector.
-XX: + UseParallelGC: set parallel collectors
-XX: + UseParallelOldGC: sets the parallel elder generation collector.
-XX: + UseConcMarkSweepGC: sets the concurrent collector.
Garbage collection statistics
-XX: + PrintHeapAtGC heap details
-XX: + PrintGCDetails GC details
-XX: + PrintGCTimeStamps: Print GC time information
-XX: + PrintTenuringDistribution: prints the age information.
-XX: + HandlePromotionFailure old-age allocation guarantee (true or false)
-Xloggc: gc. log specifies the log location
Parallel collector settings
-XX: ParallelGCThreads = n: set the number of CPUs used for parallel collector collection. Number of parallel collection threads.
-XX: MaxGCPauseMillis = n: sets the maximum pause time for parallel collection.
-XX: GCTimeRatio = n: Set the percentage of the garbage collection time to the running time. The formula is 1/(1 + n)
Concurrent collector settings
-XX: + CMSIncrementalMode: Set to incremental mode. Applicable to a single CPU.
-XX: ParallelGCThreads = n: set the number of CPUs used when the concurrent collector is used for collecting data in parallel in the young generation. Number of parallel collection threads.
Others
-XX: PermSize = 10 m and-XX: MaxPermSize = 10 m limit the size of the method area.
-XX: MaxDirectMemorySize = 10 m specifies the DirectMemory (Direct Memory) capacity. If not specified, the default value is the same as the maximum value of the JAVA heap (-Xmx.
-XX: + HeapDumpOnOutOfMemoryError allows the VM to Dump the current Memory heap Dump snapshot (. hprof file) in case of a Memory overflow exception for Analysis (such as Eclipse Memory Analysis ).

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.