A brief analysis of Java memory management

Source: Internet
Author: User

1. Heap memory and non-heap memory (non-heap memories)

Java virtual machines have a heap, where the heap is a runtime data region, where all class instances and arrays of memory are allocated, heap memory is created at the start of the Java virtual machine, is Java code-readable memory, and is left to developers, and the default free heap memory is less than 40%. The JVM will increase the heap until the maximum limit of-xmx, which can be specified by-xx:minheapfreeratio, and the default free heap memory is greater than 70%, the JVM will reduce the heap until the minimum limit of-XMS, which can be specified by-xx:maxheapfreeratio.

Non-heap memory is a memory that is outside the JVM heap, which is reserved for itself by the JVM, containing the memory required for the method area, internal processing of the JVM, or optimization, such as the Jitcompiler,just-in-time Compiler, Immediately compiled code cache), each class structure (such as running a constant pool, field, and method data), and code for methods and construction methods.

2. Status of Java objects

The GC records and manages all objects in the heap in a graph-based manner. In this way, you determine which objects are "accessible", which objects are "recoverable" and which objects are "unreachable." When an object has more than one reference, the object is "reachable"; when there is no reference to an object, the object is "recoverable"; When the object calls the Finalize () method, there is still no reference, and the object is "unreachable" when the GC determines that some objects are " Cannot be reached, the GC reclaims these memory spaces.

3. Java Memory allocation

    

A) The JVM tries to initialize a chunk of memory in Eden for the relevant Java object

b) When the Eden space is sufficient, the memory request ends;

c) The JVM attempts to release all inactive objects in Eden (this is a garbage collection of 1 or more advanced), and attempts to put some of the active objects in Eden into the survivor area if Eden space is still insufficient to fit into the new object after release

D) The survivor area is used as an intermediate swap area for Eden and old, and when the old area is sufficiently large, the objects in the Survivor area will be moved to the old area, otherwise they will remain in the survivor area.

e) When there is not enough space in the old area, the JVM performs a full garbage collection in the old area (level 0)

f) After a complete garbage collection, "Out of memory" error occurs if the survivor and old areas are still unable to store some of the objects copied from Eden, causing the JVM to be unable to create an area for the new object in the Eden area

4. Java Generational GC

The memory allocated by the Java application comes from heap memory. For example, heap memory is divided into three generations, respectively, Young,old,perm.

A) in young generation, there is a space, called the Eden Space, mainly for the new objects, and two survivor Spaces (from, to), they are always the same size, they are used to store each garbage collection survived after the object. Its garbage collection generally uses copying algorithm, the speed is fast. At each GC, the surviving objects are first copied from Eden to a survivorspace, and when the survivor space is full, the remaining live objects are copied directly to Oldgeneration. Therefore, after each GC, the Eden memory block is emptied.

b) in the old generation, it primarily stores memory objects that have a long life cycle in the application. Its garbage collection generally uses the mark-compact algorithm, slower, but reduces memory requirements.

c) Garbage collection sub-level, Level 0 for all (full) garbage collection, the old paragraph will be reclaimed garbage, 1 or more of the garbage collection, will only recover Young's garbage; "Out of memory" usually occurs after the old or perm segment garbage collection, There is still no memory space to accommodate new Java objects.

D) The cause of the full GC. New a lot of objects, no instant Active release, Eden Memory is not enough, and constantly moving objects to the old migration---full GC

5. Incremental GC

Incremental GC (Incremental GC), a GC that is typically implemented by one or a set of processes in the JVM itself, consumes the same heap space as a user program and consumes CPU at run time. When the GC process runs, the application stops running. Therefore, when the GC is running longer, the user can feel the Java program's pause, on the other hand, if the GC runs too short, the object recovery may be too low, which means that many of the objects that should be recycled are not recycled and still occupy a lot of memory. Therefore, when designing a GC, a tradeoff must be made between the pause time and the recovery rate. A good GC implementation allows the user to define the settings they need, such as some memory-constrained devices, which are very sensitive to memory usage, and want the GC to be able to accurately reclaim memory, which does not care about the speed of the program. In addition to some real-time online games, it is not possible to allow long interruptions to the program.

Incremental GC is the use of a certain recovery algorithm, a long interruption, divided into a number of small interruptions, in this way to reduce the impact of GC on the user program. Although an incremental GC may not be as efficient as a normal GC in overall performance, it can reduce the maximum downtime of a program.

The hotspot JVM provided by the Sun JDK can support incremental GC. The HotSpot JVM default GC mode is to not use Delta GC, in order to start the Delta GC, we must increase the-XINCGC parameter when running the Java program.

The implementation of the HotSpot JVM incremental GC is based on the train GC algorithm, which is based on the idea that all objects in the heap are grouped (layered) by creation and usage, that they are placed in a team with frequently high and relevant objects, and that the group is constantly tuned as the program runs. When the GC is running, it always recycles the oldest (recently infrequently accessed) objects, and if the whole group is recyclable, the GC will recycle the whole group. In this way, each GC runs only a certain percentage of unreachable objects to ensure the smooth running of the program.

6. Finalize method for Object

The Finalize method is defined in object objects. The method must be called if it implements the Finalize method before the memory occupied by an object is reclaimed. Also, the uncaught exception thrown by the method causes only the finalize execution of the object to exit. Recommendations for using the Finalize method:

A) The most important, try not to use finalize, too complicated, or let the system care better. Other methods can be defined to release non-memory resources.
b) If used, as simple as possible.
c) If used, to avoid the regeneration of objects, this is to find themselves trouble.
D) can be used to protect non-memory resources from being freed. Even if we define other methods to release non-memory resources, others may not call the method to release. In finalize it can be checked, if not released to release, the late release is better than not release.
e) Even if the object's finalize is already running, there is no guarantee that the object will be destroyed. To implement some of the actions that ensure that objects are completely destroyed, you can only rely on the class and GC interactions in Java.lang.ref.

f) After finalize runs, the object may become reachable, and the GC checks again if the object is reachable, so using finalize reduces the performance of the GC.

g) Because the time of the GC call to finalize is indeterminate, it is also indeterminate if the resource is freed in this manner.

7. Program Interaction of GC

The Java 2 platform introduces the JAVA.LANG.REF package, which includes classes that allow you to reference objects without leaving them in memory. These classes also provide limited interaction with the garbage collector (garbage collector).

A) strongreference is the kind of reference you usually build, and this reference is strong, and this is not automatically recycled by the garbage collector.

b) SoftReference is also similar to something that is dispensable. If the memory space is sufficient, the garbage collector does not reclaim it, and if the memory space is insufficient, the memory of those objects is reclaimed. The object can be used by the program as long as it is not reclaimed by the garbage collector. Soft references can be used to implement memory-sensitive caches.

D) WeakReference something that is similar to dispensable. As the garbage collector thread scans the area of memory it governs, once an object with only a weak reference is found, its memory is reclaimed, regardless of whether the current memory space is sufficient or not.

e) phantomreference is a "virtual reference", and unlike several other references, a virtual reference does not determine the object's life cycle. If an object holds only a virtual reference, it can be garbage collected at any time, just as there are no references, that is, its Get method will return null at any moment. Virtual references are primarily used to track the activities of objects that are garbage collected. It must be used in conjunction with the reference queue (Referencequeue), which is the largest difference from weak and soft references.

8. Optimization recommendations

A) If the object is being monitored, you must first remove the listener at set to null

b) Set the unused object to null as soon as possible

c) Cache objects that are used frequently

d) Interacting with reference

e) Release the reference to the useless object as soon as possible. A good idea is to use a temporary variable when the reference variable is automatically set to null after exiting the active domain, implying that the garbage collector collects the object to prevent a memory leak. For instances where pointers are still pointing, the JVM does not reclaim the resource because garbage collection will use null-valued objects as garbage, increasing the efficiency of the GC recovery mechanism;

e) In our program is inevitably a lot of string processing, avoid using string, should use a large number of StringBuffer, each string object has to occupy an area of memory;

g) Minimize the use of static variables, because static variables are global and GC will not be recycled;

h) Avoid centralizing the creation of objects, especially large objects, the JVM will suddenly require a lot of memory, which will inevitably trigger the GC to optimize the system memory environment, the declared array space is displayed, and the number of applications is very high.

i) maximize the use of object pooling techniques to improve system performance; objects with long life cycles are prone to memory leaks when they have short life-cycle objects, such as when large collection objects have large data volumes of business objects, you can consider chunking for processing.

A brief analysis of Java memory management

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.