The simplest example illustrates JVM memory allocation and recovery, and the jvm memory recovery

Source: Internet
Author: User

The simplest example illustrates JVM memory allocation and recovery, and the jvm memory recovery
I. Introduction

JVM uses generational garbage collection. In the memory space of JVM, heap space is divided into old and young generations. It is said that a large number of (more than 90%) created objects will soon die out and will be stored in the young generation, while the old generation will store instance objects with a long life cycle. The young generation is further divided into the Eden area (the garden of Eden in the Bible) and two vor zones. The new object allocation is first placed in the Eden area. The vor area serves as the buffer for the Eden and Old areas. Objects in the same vor area still survive several times of collection, it will be transferred to the old district.

1 package com. idouba. jvm. demo; 2 3/** 4 * @ author idouba 5 * Use shortest code demo jvm allocation, gc, and someting in gc. 6*7 * In details 8*1) sizing of young generation (eden space, logical vor space), old generation. 9*2) allocation in eden space, gc in young generation, 10*3) working with login vor space and with old generation.11 * 12 */13 public class SimpleJVMArg {14 15/** 16 * @ param args17 */18 public static void main (String [] args) 19 {20 demo (); 21} 22 23/** 24 * VM arg:-verbose: gc-Xms200M-Xmx200M-Xmn100M-XX: + PrintGCDetails-XX: export vorratio = 8-XX: MaxTenuringThreshold = 1-XX: + PrintTenuringDistribution25 * 26 */27 @ SuppressWarnings ("unused") 28 public static void demo () {29 30 final int tenMB = 10*1024*1024; 31 32 byte [] alloc1, alloc2, alloc3; 33 34 alloc1 = new byte [tenMB/5]; 35 alloc2 = new byte [5 * tenMB]; 36 alloc3 = new byte [4 * tenMB]; 37 alloc3 = null; 38 alloc3 = new byte [6 * tenMB]; 39} 40}

 

Iii. Execution output

The jvm parameter is used to set the size of several regions. Combined with code execution, we can observe the process of allocating and recycling objects on the stack. The execution parameters are as follows:

-verbose:gc -Xms200M -Xmx200M -Xmn100M -XX:+PrintGCDetails -XX:SurvivorRatio=8 -XX:+PrintTenuringDistribution

By setting this-Xms200M-Xmx200MSet the Java heap size to 200 MB, which cannot be extended,-Xmn100MIf 200 M is allocated to the new generation, 100-100 = M, that is, the remaining M is allocated to the old generation.-XX: Required vorratio = 8 settingsIn the new generation, the space ratio of eden to VOR is.

The result of executing the above Code is as follows:

 1 [GC [DefNew 2 Desired survivor size 5242880 bytes, new threshold 15 (max 15) 3 - age   1:    2237152 bytes,    2237152 total 4 : 54886K->2184K(92160K), 0.0508477 secs] 54886K->53384K(194560K), 0.0508847 secs] [Times: user=0.03 sys=0.03, real=0.06 secs] 5 [GC [DefNew 6 Desired survivor size 5242880 bytes, new threshold 15 (max 15) 7 - age   2:    2237008 bytes,    2237008 total 8 : 43144K->2184K(92160K), 0.0028660 secs] 94344K->53384K(194560K), 0.0028957 secs] [Times: user=0.00 sys=0.00, real=0.00 secs] 9 Heap10 def new generation   total 92160K, used 65263K [0x1a1d0000, 0x205d0000, 0x205d0000)11   eden space 81920K,  77% used [0x1a1d0000, 0x1df69a10, 0x1f1d0000)12   from space 10240K,  21% used [0x1f1d0000, 0x1f3f2250, 0x1fbd0000)13   to   space 10240K,   0% used [0x1fbd0000, 0x1fbd0000, 0x205d0000)14 tenured generation   total 102400K, used 51200K [0x205d0000, 0x269d0000, 0x269d0000)15    the space 102400K,  50% used [0x205d0000, 0x237d0010, 0x237d0200, 0x269d0000)16 compacting perm gen  total 12288K, used 360K [0x269d0000, 0x275d0000, 0x2a9d0000)17    the space 12288K,   2% used [0x269d0000, 0x26a2a3c0, 0x26a2a400, 0x275d0000)18     ro space 8192K,  66% used [0x2a9d0000, 0x2af20f10, 0x2af21000, 0x2b1d0000)19     rw space 12288K,  52% used [0x2b1d0000, 0x2b8206d0, 0x2b820800, 0x2bdd0000)

The size of the eden is 81920 K, and the size of the from and to regions in the same VOR is 10240 k. The total 92160K of the New Generation refers to the sum of eden and a region vor.

That is, the original memory

In order to demonstrate the process for the young generation to advance to the old generation. You need to set a VM parameter. MaxTenuringThreshold = 1 is set here. If this parameter is not set, MaxTenuringThreshold is set to 15 by default. When different thresholds are set, jvm processing varies in the memory. We will focus on observing the experiences of small blocks such as alloc1 in different MaxTenuringThreshold parameter settings.

In this case, MaxTenuringThreshold = 1 is added to the JVM parameters as follows:

-verbose:gc  -XX:+PrintGCDetails -XX:SurvivorRatio=8 -XX:MaxTenuringThreshold=1 -XX:+PrintTenuringDistribution

The output result is:

 1 [GC [DefNew 2 Desired survivor size 5242880 bytes, new threshold 1 (max 1) 3 - age   1:    2237152 bytes,    2237152 total 4 : 54886K->2184K(92160K), 0.0641037 secs] 54886K->53384K(194560K), 0.0641390 secs] [Times: user=0.03 sys=0.03, real=0.06 secs] 5 [GC [DefNew 6 Desired survivor size 5242880 bytes, new threshold 1 (max 1) 7 : 43144K->0K(92160K), 0.0036114 secs] 94344K->53384K(194560K), 0.0036418 secs] [Times: user=0.01 sys=0.00, real=0.01 secs] 8 Heap 9 def new generation   total 92160K, used 63078K [0x1a1d0000, 0x205d0000, 0x205d0000)10   eden space 81920K,  77% used [0x1a1d0000, 0x1df69a10, 0x1f1d0000)11   from space 10240K,   0% used [0x1f1d0000, 0x1f1d0000, 0x1fbd0000)12   to   space 10240K,   0% used [0x1fbd0000, 0x1fbd0000, 0x205d0000)13 tenured generation   total 102400K, used 53384K [0x205d0000, 0x269d0000, 0x269d0000)14    the space 102400K,  52% used [0x205d0000, 0x239f2260, 0x239f2400, 0x269d0000)15 compacting perm gen  total 12288K, used 360K [0x269d0000, 0x275d0000, 0x2a9d0000)16    the space 12288K,   2% used [0x269d0000, 0x26a2a3c0, 0x26a2a400, 0x275d0000)17     ro space 8192K,  66% used [0x2a9d0000, 0x2af20f10, 0x2af21000, 0x2b1d0000)18     rw space 12288K,  52% used [0x2b1d0000, 0x2b8206d0, 0x2b820800, 0x2bdd0000)
Iv. Process Analysis

Next we will observe the jvm Memory changes after each step of statement execution and provide resolution.

1) when executing the first statement, alloc1 allocates 2 MB space.
alloc1 = new byte[tenMB / 5];

Then, allocate 2 m storage objects in the eden area of the New Generation Based on the generational policy.

2) When executing the second statement, alloc2 allocates 50 M
alloc2 = new byte[5 * tenMB];

2 m after alloc1 is allocated, because the eden's 80 m space also has 80-2 = 78M and can accommodate the 50 m space required by allocation2, it is allocated in the eden area.

3) when the third sentence is executed, alloc3 allocates 40 M

 

alloc3 = new byte[4 * tenMB];

Still try to allocate on eden, but the eden space is only 28 M, and cannot accommodate the 40 M space required by alloc3. Therefore, a gc in the new generation is triggered to transfer the surviving objects in the Eden area to the same vor area. In this example, the alloc1 object of 2 Mb is first stored (in fact, it is copy, see the description of java garbage collection policy) to the from area, and then the alloc2 object of 50 MB is copied, obviously, the lower vor area cannot accommodate the lower alloc2 object, which is directly copied to the older generation. It must be noted that the objects copied to the same vor region will be added after one gc.

After gc in the eden area, free up space to store 40 m objects of allocation3, then alloc3 allocates 40 m objects.

4) execute the fourth sentence and leave alloc3 empty.
alloc3 = null;

This is the 40 m object allocated by alloc3 on eden, and it becomes recyclable.

5) execute 5th sentences and re-allocate 60 m space to alloc
allocation3 = new byte[6 * tenMB];

Or try to allocate in the eden area first and find that the capacity exceeds the eden area, then trigger a gc in the new generation again. First, the 40 m objects allocated on eden are directly recycled because they are not reused. Depending on the settings, the gc behavior will be slightly different this time.

First, when MaxTenuringThreshold is not set, that is, the default value is 15. After the useless 40 m recovery in the eden area, check whether the objects in the region vor meet the age threshold of the objects in the age when they were promoted to the old age. The 2 m objects in the from age is 1 and do not meet the promotion conditions, this operation will not be processed, but will add one to the age of the unprocessed object returned by the region vor, that is, the new age is 2.

The output Log also shows that the size of the young generation is changed from 43114K to 2184 k, and the total size is changed from 94344k to 53384 k, which indicates that 40 MB of useless objects are recycled.

Desired survivor size 5242880 bytes, new threshold 15 (max 15)- age   2:    2237008 bytes,    2237008 total: 43144K->2184K(92160K), 0.0028660 secs] 94344K->53384K(194560K), 0.0028957 secs] [Times: user=0.00 sys=0.00, real=0.00 secs]

After gc is made up on the young generation, 60 m of the new alloc3 space is allocated to the eden area. The heap after allocation is as follows:

The above is the gc performed without setting the promotion threshold MaxTenuringThreshold, and the allocation of alloc3 after gc.

Let's take a look at the situation when MaxTenuringThreshold is set to 1. After the useless 40 m recovery in the eden area, check whether the objects in the region vor meet the age threshold of the objects in the age when they were promoted to the old age. If the age of 2 m objects in the from area is 1, the conditions for promotion are met, then, objects of age in the region vor are copied to the old district.

The log shows that the size of the young generation is 0, indicating that the surviving objects of the young generation are moved to the old generation because the promotion conditions are met.

[GC [DefNewDesired survivor size 5242880 bytes, new threshold 1 (max 1): 43144K->0K(92160K), 0.0036114 secs] 94344K->53384K(194560K), 0.0036418 secs] [Times: user=0.01 sys=0.00, real=0.01 secs]

Similarly, after gc, space will be allocated on eden to store alloc3 objects. In this case, the Heap Structure

 

Comparing the two figures above, we can find that the difference is only that the 2 m objects in the same vor are considered to have enough survival time for the long court to be moved to the old generation. The final storage of the from region highlighted in the preceding log also reflects this difference.

Comparing the preceding two logs, we can see that the total size and the number of MaxTenuringThreshold (in fact, the value of MaxTenuringThreshold is set to 1 or 15) are not the same as those set above. The values are changed from 94344k to 53384 kb, that is, useless objects in the 40 M eden region are recycled. During the nth gc, the eligible promotion conditions were changed from the primary vor to the old generation. If the conditions were not met, the total size of the heap remained in the primary vor region.

V. Final

The simplest example above illustrates how to adjust and recycle objects in the jvm stack if they are allocated and the space is insufficient. I hope I can have a basic understanding of the jvm stack structure and gc ideas. Of course, the relevant parameters (in fact, the mechanism is reflected) are far more complex than this. They have a lot of details and are more experienced in practice.

Appendix: Main Parameters

JVM startup settings have many parameters. You can refer to the Java HotSpot VM Options description in. The example involves the most basic parameters. Here we only describe the parameters involved.

Parameter Name Description Default Value Description
-Xms Initial heap size 1/64 of physical memory (<1 GB) By default (the MinHeapFreeRatio parameter can be adjusted) when the free heap memory is smaller than 40%, the JVM will increase the heap until the maximum limit of-Xmx.
-Xmx Max heap size 1/4 of physical memory (<1 GB) By default (the MaxHeapFreeRatio parameter can be adjusted) when the free heap memory is greater than 70%, the JVM will reduce the minimum heap limit until-Xms
-Xmn Young Generation size   Note: The size here is (eden + 2 kernel vor space). It is different from the New gen shown in jmap-heap.
Total heap size = size of the young generation + size of the old generation + size of the persistent generation.
After the young generation is increased, the size of the old generation will be reduced. This value has a great impact on system performance. Sun officially recommends setting it to 3/8 of the total heap.
-XX: Invalid vorratio Ratio of Eden to vor   If the value is set to 8, the ratio of two vor zones to One Eden zone is. One vor zone occupies 1/10 of the total number of young generations.
-XX: + PrintGC Enable GC log Printing Disabled by default Enable GC log printing. The print format is as follows:
[Full GC 131115 K-> 7482 K (1015808 K), 0.1633180 secs]
This option can be dynamically enabled through com. sun. management. HotSpotDiagnosticMXBean API and Jconsole.
See http://java.sun.com/developer/technicalArticles/J2SE/monitoring/#Heap_Dump
-XX: + PrintGCDetails Print GC recovery details. Introduced in 1.4.0, disabled by default The print format is as follows:
[Full GC (System) [Tenured: 0 K-> 2394 K (466048 K), 0.0624140 secs] 30822 K-> 2394 K (518464 K), [Perm: 10443 K-> 10443 K (16384 K)], 0.0625410 secs] [Times: user = 0.05 sys = 0.01, real = 0.06 secs]
This option can be dynamically enabled through com. sun. management. HotSpotDiagnosticMXBean API and Jconsole
See http://java.sun.com/developer/technicalArticles/J2SE/monitoring/#Heap_Dump
XX: + PrintTenuringDistribution View the threshold value of the new life cycle after each minor GC   Prints the object lifecycle information. The print format is as follows:
[GC
Desired primary vor size 4653056 bytes, new threshold 32 (max 32)
-Age 1: 2330640 bytes, 2330640 total
-Age 2: 9520 bytes, 2340160 total
204009 K-> 21850 K (515200 K), 0.1563482 secs]
Age1 2 indicates the size of objects that survive after GC of 1st and 2.
-XX: MaxTenuringThreshold Maximum age of spam. Objects that are still alive after this threshold value are recycled in the VOR region and moved to the old generation.   If it is set to 0, the young generation object directly enters the old generation without going through the 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

Editable Image Attachment: jvm-allocation-and-gc

 

Original article. To maintain consistent, up-to-date, and traceable versions of the document, please note:Reprinted from idouba

Link:The simplest example illustrates JVM memory allocation and recovery.


Can I change the JVM memory allocation in the java installation directory?

Run the java command.
Use java-option to modify parameters.
In addition, tomcat is loaded through the configuration file during eclipse startup.

The details are as follows:
When installing Java development software, two folders are installed by default, one JDK (Java Development Toolkit) and one JRE (Java Runtime Environment, including JVM. If you only run the Java program, JRE is enough, and JDK is only used by developers.
1. Configure JVM memory

1. Configure JVM memory Parameters
-The maximum value of XmxJavaHeap. The default value is 1/4 of the physical memory. The optimal value depends on the physical memory size and other memory overhead in the computer;
-The initial value of XmsJavaHeap. It is best to set-Xms and-Xmx to the same value on the Server JVM. The default value can be retained on the JVM of the development and testing machine;
2. How to configure JVM memory allocation:

(1) When starting and using JVM at a command prompt (only effective for the currently running class)
Java-Xmx128m-Xms64m-Xmn32m-Xss16mTest

(2) When JVM is started and used in an integrated development environment (such as eclipse:
Method 1:
Open eclipse. ini in the eclipse root directory. The default content is (the JVM memory allocation for running the current development tool is set here ):
-The vmargs-Xms40m-Xmx256m-vmargs represents the following parameter settings for the virtual machine, where you can modify the parameter value, in addition, eclipse. you can also set non-heap memory in ini, for example,-XX: PermSize = 56 m,-XX: MaxPermSize = 128 m.

The parameter values set here can be displayed in the development tool's status bar through the following Configuration:
Create the file options in the eclipse root directory. The file content is org. eclipse. ui/perf/showHeapStatus = true.
Modify the eclipse. ini file under the eclipse root directory and add the following content at the beginning:
-Debugoptions-vmjavaw.exe restart eclipse, and the JVM information is displayed in the following status.

Method 2:
Open eclipse-window-preference-Java-installed JRE (for all java programs running in the current development environment)
Edit the currently used JRE and enter-Xmx128m-Xms64m-Xmn32m-Xss16m in the default VM Parameters

Method 3:
Open eclipse-run-Java application (only effective for the configured java class)
Select the class-independent variable for which you want to set the memory allocation, and enter-Xmx128m-Xms64m-Xmn32m-Xss16m In the VM independent variable

NOTE: If both the second and third settings are performed in the same development environment, the second setting takes effect, and the third setting is invalid, for example:
The development environment is set to-Xmx256m, and the Test class is set to:-Xmx128m-Xms64m, the setting that takes effect when Test is run is:
Xmx256m-Xms64m

(3) When JVM is started and used in a server environment (such as Tomcat) (This takes effect for the Java program in the current server environment ):
A. Set environment variables:
Variable name: CATALINA_OPTS
Variable value:-Xmx128m-Xms64m-Xmn32m-Xss16m

B. Open the bin folder under the Tomcat root directory, edit catalina. bat, replace % CATALINA_OPTS % (in total) with:-Xmx128m-Xms64m-Xmn32m-Xss16m

Ii. View JVM memory configuration information
Runtime. getRuntime (). maxMemory (); // maximum available memory, corresponding to-Xmx
Runtime. getRuntime (). freeMemo ...... remaining full text>

How to manage jvm memory

Typical settings:
• Java-Xmx3550m-Xms3550m-Xmn2g-Xss128k
-Xmx3550m: sets the maximum available JVM memory to 3550 MB.
-Xms3550m: Set JVM to enable the memory to be 3550 MB. This value can be set to the same as-Xmx to avoid JVM re-allocating memory after each garbage collection.
-Xmn2g: Set the young generation to 2 GB. Total heap size = size of the young generation + size of the old generation + size of the persistent generation. The permanent generation usually has a fixed size of 64 m. Therefore, increasing the size of the young generation will reduce the size of the old generation. This value has a great impact on the system performance. Sun officially recommends 3/8 of the total heap configuration.
-Xss128k: Set the stack size of each thread. After JDK 256, the size of each thread stack is 1 MB, and the size of each previous thread stack is K. The memory size required for more application threads is adjusted. Reduce this value to generate more threads in the same physical memory. However, the operating system still has a limit on the number of threads in a process. It cannot be generated infinitely. The experience is between 3000 and ~ About 5000.
• Java-Xmx3550m-Xms3550m-Xss128k-XX: NewRatio = 4-XX: Export vorratio = 4-XX: MaxPermSize = 16 m-XX: MaxTenuringThreshold = 0
-XX: NewRatio = 4: Set the ratio of the young generation (including Eden and two region vor regions) to the old generation (excluding the permanent generation ). If this parameter is set to 4, the ratio of the young generation to the old generation is, and the young generation accounts for 1/5 of the entire stack.
-XX: Region vorratio = 4: Set the ratio of Eden to region vor in the young generation. If this parameter is set to 4, the ratio of two vor zones to One Eden zone is, and one vor zone accounts for 1/6 of the young generation.
-XX: MaxPermSize = 16 m: sets the persistent generation size to 16 m.
-XX: MaxTenuringThreshold = 0: sets the maximum age of spam. If it is set to 0, the young generation object directly enters the old generation without going through the 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, added an overview of being recycled in the young generation.

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.