The JVM memory is very simple and interesting Java

Source: Internet
Author: User
Tags garbage collection memory usage xms

When reading this article, at least first of all, the concept of the JVM, working principle, structure composition, have certain basic understanding, the nonsense does not say much, this article is straight to the point, directly to work more common concepts: class, Class object, instance object, static method, Non-static method, static attribute, non-static attribute, etc. directly into the use and allocation of JVM memory, through these principles to understand the static methods in Java and static properties of the problem, followed by the JVM memory stack model, mainly describes the structure of the JVM memory stack, and finally the JVM memory parameter settings, mainly describes the memory settings to prevent memory overflow.

One, from the JVM memory angle to recognize static access, static properties

In the JVM, where memory is divided into two parts, stack (stack) and heap (heap), we understand stack and heap from the perspective of the JVM's memory management principles, and use these principles to understand the problems of static methods and static properties in Java.

The general JVM's memory is divided into two parts: Stack and heap.

Stack (stack) is the memory instruction area of the JVM. Stack management is simple, push a certain length byte of data or instruction, stack pointer stack corresponding byte displacement; pop a certain byte length data or instruction, stack pointer Pinball. The stack is fast, easy to manage, and the data or instruction byte length of each operation is known. So Java basic data type, Java instruction code, constants are stored in stack.

The Heap (heap) is the memory data area of the JVM. Heap's management is complex, allocating an indefinite amount of memory each time, specifically to hold an instance of the object. Allocating a certain amount of memory in the heap to save the object instance is actually just saving the object instance's property value, the attribute's type and the object's own type tag, and so on, does not save the object's method (the method is the instruction, saves in the stack), in heap A certain amount of memory is allocated in the Save object instance and the object's serialization comparison is similar. When an object instance is allocated in heap, a 4-byte heap memory address needs to be stored in the stack to locate the object instance in the heap, so that it is easy to find the object instance.

Because stack memory management is sequentially allocated, and fixed length, there is no memory recovery problem, and heap is random allocation of memory, indefinite length, there are memory allocation and recycling problems; so there is another GC process in the JVM that periodically scans heap, It scans heap from the 4-byte object address stored in the stack, locates the objects in heap, makes some optimizations (such as merging free memory blocks, and so on), and assumes that the areas not scanned in heap are idle. All the refresh (in fact, the useless object that lost the object address in the stack is removed), which is the process of garbage collection;

Image: JVM Architecture

The first thing we need to figure out is what data is and what is the instruction. Then figure out where the object's methods and objects ' properties are stored.

1 The method itself is the operation code part of the instruction, which is stored in stack;

2 The internal variable of the method as the operand part of the instruction, following the opcode of the instruction, stored in the stack (which is actually a simple type saved in stack, the object type holds the address in the stack, and the value is stored in the heap); the instruction opcode and instruction operand above constitute the complete Java Instructions.

3 The object instance includes its property value as data and is stored in the data area heap.

Non-static object properties are stored in heap as part of an object instance, and object instances must be accessible through an address pointer saved in the stack. Therefore, the ability to access an object instance and its Non-static property values depends entirely on the availability of an object instance's address pointer in the stack.

The difference between a non-static method and a static method:

A non-static method has a significant difference from a static method: A Non-static method has an implied incoming parameter, which is given to it by the JVM, regardless of how we write the code, which is the address pointer of the object instance in the stack. Therefore non-static methods (instruction code in stack) can always find their own private data (object property values in heap). Of course, a non-static method must also obtain the implied parameter, so a non-static method must first get an instance of an object to obtain the address pointer in the stack before it is invoked, otherwise the JVM will not be able to pass the suppressed parameters to the Non-static method.

The static method does not have this implied parameter and therefore does not require a new object, which can be invoked as long as the class file is ClassLoader load into the stack of the JVM. Of course, at this point the static method is not accessing the object properties in the heap.

Summarize the process:

When a class file is entered into the JVM by ClassLoader load, the method instruction is stored in the stack, and the heap area has no data at this time. Then the program registers the execution instruction, if is the static method, executes the instruction code sequentially, certainly at this time the instruction code is unable to access the heap data area, if the Non-static method, because the implied parameter does not have the value, can the error. Therefore, before the Non-static method executes, the new object is first assigned, the data is allocated in the heap, and the address pointer in the stack is given to the Non-static method, so that the program technology executes the instruction sequentially, and the instruction code can access the heap data area at this time.

Static properties and Dynamic properties:

As mentioned earlier, object instances and dynamic properties are stored in heap, and heap must be accessible through the address pointer in the stack to the instruction (the method of the Class). It is therefore possible to infer that static properties are stored in the stack, unlike dynamic properties stored in heap. Because they are all in stack, and the instructions and data in the stack are fixed, it is easy to figure out the offsets, and therefore no matter what instruction (the method of the class) can access the static properties of the class. Also because static properties are stored in the stack, they have global properties.

So, in the JVM, static properties are stored in the stack instruction memory area, and dynamic properties are stored in the heap data memory area.

Second, stack memory model of JVM

1. Java stack

The Java stack is associated with each thread, and the JVM allocates a certain amount of stack space to the thread when it creates each thread. It is primarily used to store local variables during thread execution, the return value of methods, and the method invocation context. Stack space is released as the thread terminates. Stackoverflowerror: If the stack space is not available during the thread execution, the JVM throws the exception, which is usually caused by a dead recursion.

2. Heap

Java heap is a memory area shared by all threads, and the heap is used to hold various Java objects, such as arrays, thread objects, and so on.

2.1 Generation

The JVM heap can generally be divided into the following three parts:

Perm Permanent Zone

Perm mainly save Class,method,filed objects, this section of the space generally will not overflow, unless a lot of loading the class, but when it comes to hot deployment of the application server, sometimes encounter Java.lang.OutOfMemoryError: PermGen space error, the cause of this error is likely to be redeployed every time, but after redeployment, class classes have not been unloaded, causing a large number of class objects saved in the perm, in this case, A general restart of the application server can resolve the problem.

Tenured old

Tenured the main preservation life cycle of the object, generally some old objects, when some objects in young replication transfer a certain number of times, the object will be transferred to the tenured area, generally if the system with the application level of caching, Objects in the cache are often moved to this interval.

Young Youth District

The young district is divided into three parts, the Eden area and the two survivor areas of the same size, of which only one of them is used in the Survivor interval, and the other is a copy object for garbage collection when the young is full, minor The GC will move the surviving objects into the free survivor interval, according to the JVM's strategy, after several garbage collections, the objects that are still alive in survivor will be moved to the tenured interval. Sometimes the area often encounters Java.lang.OutOfMemoryError:Java heap space errors.

2.2 Sizing the Generations

The JVM provides the appropriate parameters to configure the memory size. As described above, the heap in the JVM is divided into 3 large intervals, while the JVM also provides some options for controlling the size of the young,tenured.

Total Heap

-XMS: Specifies the initialization of memory after the JVM's initial startup

-XMX: Specifies the maximum memory for the JVM heap, and allocates the memory of the specified size of the-XMX parameter to the JVM after the JVM is started, but not necessarily all, and the JVM adjusts the memory that is actually used for the JVM based on the-XMS parameters

The difference between the-XMX-XMS is the size of three virtual spaces

Young Generation

-xx:newratio=8 means the ratio of tenured and young is 8:1, so EDEN+2*SURVIVOR=1/9

Heap Memory

-xx:survivorratio=32 means that the ratio of Eden to a survivor is 32:1, a survivor that accounts for 1/34 of young.

The-XMN parameter sets the size of the young generation

Perm Generation

-xx:permsize=16m-xx:maxpermsize=64m

Thread Stack

-xx:xss=128k

3. Benefits of Stack separation

Let's say object-oriented design, of course, in addition to the benefits of the maintainability, reusability and extensibility of object-oriented design, we look at how the object-oriented approach leverages stack separation. If you understand object-oriented design from the perspective of the Java memory model, we will find that it perfectly represents the heap and stack, the object's data in the heap, and we write those methods are generally running in the stack, so object-oriented design is a very perfect way to design, it is a perfect unified data storage and operation.

Third, the JVM's heap memory parameter settings

PermGen space: The full name is permanent Generation. is a permanently preserved area for storing class and meta information, and class is placed in the area when it is load heap space: store instance.

GC (garbage Collection) should not clean up the PermGen space, so if your app will load a lot of class, it's likely that PermGen space error will occur

Java Heap is divided into 3 districts

1.Young

2.Old

3.Permanent

Young saves a newly instantiated object. When the area is filled, the GC moves the object to the old area. The permanent area is responsible for saving reflection objects.

The heap allocation of the JVM can be set using the-X parameter:

-xms Initial Heap Size

-xmx java heap max value

The heap size of-xmn young generation

The JVM has 2 GC threads

The first thread is responsible for reclaiming the young area of heap.

The second thread, when heap is insufficient, traverses the heap and upgrades young to the older area

The size of the older area equals-xmx minus-xmn, and the-XMS value cannot be set too large because the second thread is forced to run, which degrades the performance of the JVM.

Why some programs frequently occur with GC. There are the following reasons:

1. System.GC () or RUNTIME.GC () is invoked within the program.

2. Some middleware software calls its own GC method, at which point you need to set parameters to prohibit these GC.

3. Java heap is too small, the general default heap values are very small.

4. Frequently instantiate objects, release objects try to save and reuse objects at this time, such as using StringBuffer () and string ().

If you find that after each GC, Heap's remaining space will be 50% of the total space, which means that your heap is in a healthy state, and many server-side Java programs have a 65% more space left over each GC.

Experience:

1. The server-side JVM is best to set-XMS and-xmx to the same value. In order to optimize GC, it is best to have the-xmn value equal to about 1/3 of-XMX.

2. A GUI program is best to run the GC once every 10-20 seconds, each time within half a second.

Attention:

1. Increasing the size of the heap may reduce the frequency of the GC, but it also increases the time for each GC. And when the GC runs, all the user threads will be paused, i.e., during the GC, the Java application does not do any work.

2. The heap size does not determine the amount of memory used by the process. The memory usage of a process is greater than the value defined by-XMX, because Java allocates memory for other tasks, such as stack for each thread.

Stack's setting

Each thread has his own stack.

-XSS: Stack size per thread

The size of the stack limits the number of threads. The-XSS parameter determines the stack size, such as-xss1024k. If the stack is too small, it can also cause stack overflow.

Hardware environment

The hardware environment also affects the efficiency of the GC, such as the type of machine, memory, swap space, and number of CPUs. If your program needs to create many transient objects frequently, it will cause the JVM to frequent GC. In this case you can increase the memory of the machine to reduce the use of swap space.

4 Kinds of GC

1. The first is a single-threaded GC and is also the default GC, which is applicable to single CPU machines.

2, the second is throughput GC, is a multi-threaded GC, suitable for multiple CPUs, the use of a large number of threads of the program. The second GC is similar to the first GC, except that the GC is multi-threaded in the collection of young, but in the old and the first, it still takes a single thread. The-XX:+USEPARALLELGC parameter starts the GC.

3. The third type is concurrent low Pause GC, similar to the first, for multiple CPUs, and requires shortening the time that the GC causes the program to stagnate. This GC can run the application at the same time as the old zone's recycle. The-XX:+USECONCMARKSWEEPGC parameter starts the GC.

4. The fourth type is incremental low Pause GC, which is suitable for shortening the time that the GC causes the program to stagnate. This GC can reclaim some old area objects while recovering from the young area. The-XINCGC parameter starts the GC.

Set the JVM memory for a single file

The default Java virtual machine size is relatively small, in the processing of large data Java will be an error: Java.lang.OutOfMemoryError. To set the JVM memory method, for individual. Class, you can set the JVM memory for test runtime in the following ways:

java-xms64m-xmx256m Test

-XMS is to set the size of memory initialization

-XMX is to set the maximum available memory size (preferably not more than the physical memory size)

Tomcat Boot JVM Memory settings

Linux:

In the/usr/local/apache-tomcat-5.5.23/bin directory of catalina.sh add: java_opts= '-xms512m-xmx1024m ' to add "M" description is MB, otherwise it is KB, Low memory is reported when you start Tomcat.

-XMS: Initial value

-XMX: Max value

-XMN: Min-Value windows

Join in front of the Catalina.bat

Set java_opts=-xms128m-xmx350m if Tomcat is started with Startup.bat, The OK setting takes effect. Allocate 200M of memory successfully. But if you do not perform startup.bat boot tomcat instead of using Windows's system service to start the Tomcat service, the above setting does not take effect, that is, set java_opts=-xms128m- Xmx350m didn't work. 200M of memory allocated above is oom. The Windows service executes Bin\tomcat.exe. He reads the values in the registry, not the Catalina.bat settings. Solution:

Modify Registry Hkey_local_machine\software\apache SOFTWARE Foundation\tomcat Service manager\tomcat5\parameters\javaoptions

The original value is

-dcatalina.home= "C:\ApacheGroup\Tomcat 5.0"

-djava.endorsed.dirs= "C:\ApacheGroup\Tomcat 5.0\common\endorsed"

-xrs joins-xms300m-xmx350m

Restart the Tomcat service, Setup takes effect

Weblogic

In WebLogic, you can set the size of each domain virtual memory in Startweblogic.cmd, and the default setting is in Commenv.cmd.

Jboss

The default can be used for 64MB of memory

$JBOSSDIR $/bin/run.config

java_opts = "-server-xms128-xmx512"

Related Article

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.