Java memory composition and garbage collection mechanism

Source: Internet
Author: User
Tags jconsole

See the time to look for work, usually in the laboratory also do a lot of projects, but in the end, assuming that the interviewer asked me what I usually do, I do not know where to start, can also say I do not know what to say. Predecessors have long said that the computer industry needs to continue to learn, but also need to accumulate constantly, ask yourself to meet a lot of problems, but also solve a lot of problems, but in the end, it seems that there is no impression! In preparing to find a job, will usually some of the research, Daoteng to record it again! Because I am the first time to write a blog, writing is not very good, the content may also have a lot of references are predecessors, but the re-collation, select, but also let themselves in the process of re-study, deepen the impression!

First, memory composition

When I do the project,Tomcat will often report "Java.lang.OutOfmemoryError:PermGen Space" error , the online solution is many, I generally follow these methods to change the configuration of tomcat OK! Some time ago, help the teacher to the Beijing deployment project, under a Tomcat deployed three processes. It was OK to access the first two projects, but the same error occurred while accessing the third project. This time I have studied the problem in depth.

To understand the nature of this problem, you need to know the memory composition of the JVM. Open the JDK's Jconsole.exe to see how the JVM is running :

As you can see, the JVM primarily manages two types of memory: heap and non-heap. To borrow a picture, you can see more clearly:

1. Method area

The method area, like the Java stack, is an area of memory shared by each thread that stores the class information, constants, static variables, instant compiler-compiled code, and so on, that have been loaded by the virtual machine. It is a non-heap "non-heap".

In the hotspot virtual machine, many people have the method area as a permanent generation, in fact, only in the hotspot to exist in the method area, in other virtual machines do not have a method area of the argument. The above-mentioned tomcat "Java.lang.OutOfmemoryError:PermGen Space" error is that the area is full. All the error occurred when accessing the third project because the relevant class file for the project was loaded into the JVM's method area the first time the project was accessed.

2. Program counter

Program counter is a very small memory space, it is actually very simple, is the current thread execution of the bytecode line number indicator. In the hotspot virtual machine, the bytecode interpreter works by changing the value of this counter to select the next byte code instruction, branch, loop, jump, exception handling, etc. to execute.

3. Java Virtual machine stack

Java Virtual machine stacks are the same as program counters, and are thread-private. In Java, the stack in the JVM records the method invocation of the thread. In the process of running a thread, if there is a new method call, the stack for that thread will add a storage unit, the frame. In a frame, the parameters, local variables, and return addresses of the method call are saved.

  4. Local Method Stack

The local method stack is similar to the virtual machine stack, except that the Java virtual machine executes the Java method, and the local method area executes the native method, such as the bootstrap ClassLoader called when the JVM loads a class in the JRE, which is implemented by C + +.

5. Heap (Storing properties of objects, allocating memory space to each property)

In Java programmers heap, certainly not unfamiliar, heap is the most used, is also the program ape most concerned about a piece of memory area. All the threads in the heap share a region of memory that is created when the virtual machine is started, and the only purpose of this memory area is to hold object instances where almost all of the object instances are allocated.

Second, garbage collection mechanism (GC)

When it comes to memory allocation, you have to say that the memory is recycled. familiar with C + + programming should know that in programming, we need to manually release the objects in the heap, if you forget, then the area will never be released, accidentally will be a memory leak, generally only restart the machine! Java provides a garbage collection mechanism (GC) that can automatically empty objects that are no longer used in the heap! This feature is pretty nice, but on the other hand, garbage collection takes more time to compute, which is one reason why Java is slower than C + +. For Java GC, personally think @vamei predecessors write is also good, in this reference:

In Java, objects are used by reference (the object is like a deadly poison, a reference to a forceps used to extract poison). If there is no longer a reference to the object, then we can no longer invoke or manipulate the object. Such objects will not be reachable (unreachable). garbage collection is used to free up memory occupied by unreachable objects. This is the basic principle of garbage collection. (Unreachable objects are dead objects, garbage collected by garbage collection)

Early garbage collection takes the mechanism of reference counting (reference counting) . Each object contains a counter. When there is a new reference to the object, the counter is incremented by 1. When the reference is removed, the counter is reduced by 1. When the counter is 0 o'clock, it is considered that the object can be garbage collected.

However, one possible problem is that if there are two objects that are circular references (cyclic reference), such as two objects referencing each other, and there is no other reference (point A or point B) At this time, we actually simply cannot reach both objects by reference. Therefore, we can find all the reachable objects by using the stack and static data as root (Root), starting from the root and following all the references. in other words, a reachable object must be referenced by the root, or by another reachable object.

Orange to reach, green unreachable

Garbage collection by the JVM is a mixture of various mechanisms. Depending on the health of the program, the JVM decides which garbage collection to use. Can see the monitoring of the Jconsole:

Let's start by knowing "Mark and Sweep". Under this mechanism, each object will have tag information that indicates whether the object is reachable. When garbage collection starts, the Java program pauses to run. The JVM starts from the root, finds all reachable objects, and marks (Mark). The JVM then needs to scan the entire heap, find the remaining objects, and empty the memory that these objects occupy.

The other is "copy and Sweep." Under this mechanism, the heap is divided into two regions. The object always survives in one of two regions. When garbage collection starts, the Java program pauses to run. The JVM starts from the root, finds reachable objects, copies the reachable objects into a blank area, and arranges them tightly, modifying the change in the reference address caused by the movement of the object. Finally, empty the entire area that the object originally survived, making it a new blank area.

  As you can see, "Copy and Sweep" requires more complex operations, but also allows objects to be tightly arranged to avoid possible gaps in "mark and sweep". When you create a new object, "Copy and Sweep" provides a large contiguous space. Therefore, if the objects are compared to "longevity", then it applies to "Mark and sweep". If the object's "metabolism" is more active, then it applies to "copy and Sweep."

The above two mechanisms are combined by generational recycling (generational collection). Each object record has its generation (generation) information. The so-called generation refers to the number of garbage collections that the object experiences. The older the object, the longer it takes to survive in memory.

According to a statistical observation of Java programs, the longer the generation of objects, the less likely it is to be garbage collected (the richer the rich, the poorer the poor). Therefore, when we are in the garbage collection, we should pay more attention to those young objects. Now, specifically, look at the heap in the JVM:

We see that the heap is divided into three generations. The permanent generation (permanent generation) survives in the class object. These objects are not garbage collected. The younger generation (young generation) and the mature generation (tenured generation) need to be garbage collected. The object generation in the younger generation is closer, and the object generation in the mature generation is longer.

Generation

The younger generation is further divided into three districts

    • Eden (Eden): Newborn objects live in the region. The new object refers to the newly created object from the last GC.

The new object lives in the Garden of Eden

    • From, to: these two regions are equal in size, equivalent to two regions in copy and Sweep .

When a new object cannot be placed in the Eden area, minor collection is started. The JVM uses the policy of copy and sweep to copy the Eden Zone and the reachable objects from the from zone to the to area. After a garbage collection, the Eden Zone and the from zone are emptied, and the to area is tightly stocked with surviving objects. Subsequently, the from zone becomes the new to zone and the to zone becomes the new from zone.

If the minor collection is found to be out of the area, then part of the object is put into the mature generation. On the other hand, even if the to area is not full, the JVM will still move long enough to mature generations.

If the mature generation fills the object and cannot move into the new object, the major collection is triggered. The JVM uses the mark and sweep strategy for garbage collection of mature generations.

The first time to write a blog or learn from the comparison of Doha, hehe, but his own writing has been harvested! The great God said, no matter more or less, whether simple or difficult, feel that meaningful can be written down, the accumulation of weight in the share!

  

Java memory composition and garbage collection mechanism

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.