Java garbage collection mechanism and Memory leakage, java garbage collection Leakage

Source: Internet
Author: User

Java garbage collection mechanism and Memory leakage, java garbage collection Leakage

1. Introduction to Java Memory leakage

First, let's clarify the concept of Memory leakage: Memory leakage refers to the Dynamic Allocation of memory during the program running, but the memory is not released at the end of the program, resulting in the unavailability of this memory, this is the memory

This problem can be solved by restarting the computer, but memory leakage may occur again. Memory leakage has nothing to do with hardware, which is caused by software design defects.

The reason for Memory leakage in Java is very clear, that is, the reference of long declaration period objects holding short declaration period objects is likely to cause memory leakage. Although short-lived objects are no longer needed

When a periodic object holds its reference, it cannot be recycled by GC. This is the scenario where Java Memory leakage occurs.

Examples of java Memory leakage scenarios:

When we constantly add elements to the Collection class without corresponding deletion mechanism, resulting in memory usage, this may not necessarily cause memory leakage. When the collection class is only a local change

When the method is executed and exited, it will be recycled by GC, but it is afraid that the collection class is a global attribute (such as a static variable in the class ), this will cause the collection class to occupy only the memory

This causes memory leakage. Therefore, when using global collection classes, we should pay attention to providing appropriate deletion policies or regular cleaning policies.

Memory leakage can be divided into four categories:

(1) Frequent Memory leakage: code with Memory leakage will be executed multiple times, and a piece of memory will be leaked each time it is executed.

(2) Occasional Memory leakage: code with Memory leakage occurs only in some specific environments, and the frequent occurrence is opposite to the occasional occurrence. For a specific environment, sporadic, that is, frequent. Therefore, test

Testing Methods and testing environments are important for detecting memory leaks.

(3) One-time memory leakage: code with Memory leakage will only be executed once, so that there is always a memory in the memory that is unavailable.

(4) Implicit Memory leakage: During program execution, the memory is continuously allocated until the program ends. Strictly speaking, there is no memory leakage, because the program is finally released

All applied memory. However, for a server program, it is often executed continuously for many days or even several months, so that memory overflow will occur sooner or later. Therefore, we call this type of Memory leakage as implicit

Memory leakage.

2. Java memory overflow Problems and Solutions

The memory managed by JVM is roughly divided into three different types of memory areas:

Generation space (permanent storage area), Heap space (Heap area), and JavaStacks (Java stack ). The permanent storage area stores the Class and Meta information. The Class is loaded for the first time.

When stored in the PermGenspace area, the content that the Class needs to store mainly includes methods and static attributes. The heap area is used to store Class instances (objects). The content to be stored for objects is mainly non-static.

Attribute. After an object instance is created with new, the object instance is stored in the heap area, and the space is also managed by the jvm garbage collection mechanism. Java stack is similar to the stack functions of most programming languages, including assembly languages.

It is similar to the input and output parameters of the main basic type variables and methods. Each thread of a Java program has an independent stack. Memory space that is prone to memory overflow includes:

Permanent Generation space and Heap space.

First OutOfMemoryError: PermGenspace

The original intention of this problem is that the program uses a large number of jar or class, so that the Java Virtual Machine does not have enough space to load the class, which is related to PermanentGeneration space. There are two solutions to this problem:

(1) Increase the values of the XX: PermSize and XX: MaxPermSize parameters in the Java Virtual Machine. The XX: PermSize indicates the size of the initial permanent storage area, and the XX: MaxPermSize indicates the maximum permanent storage area.

Small. For example, for tomcat6.0, in catalina. sh or catalina. in the bat file, a series of environment variable names are added at the end (about 70 rows): JAVA_OPTS = "-XX: PermSize = 64 M-

XX: MaxPermSize = 128 m "if it is a windows server, you can also set it in the system environment variable. I feel that this memory overflow is very likely to occur when I use tomcat to release a sprint + struts + hibernate architecture program.

Error. Using the above method, I successfully solved the problem of frequent downtime of the tomcat server where the ssh project is deployed.

(2) Clear the jar files under web-inf/lib in the application. If multiple applications are deployed in tomcat, many applications use the same jar files, common jar files can be moved to the common lib of tomcat to reduce repeated class addition.

. This method is recommended by some people on the Internet. I have never tried it, but I feel that it cannot be reduced too much space. The most reliable method is the first one.

OutOfMemoryError: Javaheap space

This problem occurs because there are too many objects created by the Java Virtual Machine. During garbage collection, the Heapspace allocated by the virtual machine to the Heapspace is full. There are two ways to solve such problems

Path:

(1) Check the program to see if there is an endless loop or a large number of objects are repeatedly created unnecessary. After finding the cause, modify the program and algorithm.

I used to write a K-Means text clustering algorithm for text clustering of tens of thousands of text records (about 10 feature vectors per record, java heap

Space memory overflow was solved by modifying the program.

(2) increase the Xms (initial heap size) and Xmx (maximum heap size) parameters in the Java Virtual Machine. For example, setJAVA_OPTS =-Xms256m-Xmx1024m

3. Java GC Mechanism

A good programmer must understand the principles of GC, how to change the performance of GC, and how to have limited interaction with GC, because some programs have high performance requirements, for example, embedded systems and real-time systems, only

Only by comprehensively improving the memory management efficiency can the program performance be effectively improved.

Basic Principles of GC:

Java memory management is actually object management, including object allocation and release.

For programmers, The new Keyword is used to allocate objects. Releasing an object is to assign null values to all references of the object so that the program cannot access this object. This is called the 'inaccessibility 'state, GC is responsible for collecting

Memory space of an object in an inaccessible state.

For GC, when a programmer creates an object, GC starts to monitor the object size, address, and usage. Generally, GC uses a directed graph to manage all objects in heap. In this way

To determine which objects are reachable and which objects are inaccessible. When GC determines that some objects are inaccessibility, GC has the responsibility to recycle these objects. However, to ensure that GC can be implemented on different platforms

The Java specification does not strictly regulate many GC behaviors. For example, there are no clear rules on the types of recycling algorithms used and when to recycle them. Therefore, no

The implementers of the same JVM often have different implementation algorithms.

This also brings many uncertainties to the Development of Java programmers. This article studies several issues related to GC and strives to reduce the negative impact of such uncertainty on Java programs.

Incremental GC (Incremental GC)

GC is usually implemented by one or a group of processes in JVM. It also occupies heap space like the user program, and CPU usage during runtime. the application stops running when the GC process is running.

Therefore, when GC runs for a long time, the user can feel the pause of the Java program. On the other hand, if GC runs for a short time, the object recovery rate may be too low, this means there are still many objects to be recycled.

It is recycled and still occupies a large amount of memory. Therefore, we must weigh the pause time and recovery rate when designing GC. A good GC implementation allows users to define their desired settings, such

Limited storage devices are very sensitive to memory usage. In the hope that GC can accurately recycle memory, it does not care about program speed slowdown. In addition, some real-time online games cannot allow long periods of time for programs.

Disconnected. Incremental GC divides a long interrupt into many small interruptions through a certain collection algorithm, which reduces the impact of GC on user programs. Although the incremental GC Performance

It may not be as efficient as normal GC, but it can reduce the maximum pause time of the program. The HotSpot JVM provided by Sun JDK supports incremental GC. The default GC mode of HotSpot JVM is that incremental GC is not used.

To start the incremental GC, we must add the-Xincgc parameter when running the Java program.

HotSpot JVM incremental GC adopts the Train GC algorithm. The basic idea is that all objects in the heap are grouped (layered) according to the creation and usage, and will be frequently used and highly correlated.

Objects are placed in a group, and the group is constantly adjusted as the program runs. When GC is run, it always recycles the oldest (rarely accessed recently) Objects first. If the whole group is recyclable objects, GC returns the whole group

. In this way, each GC operation only recycles a certain percentage of inaccessible objects to ensure smooth operation of the program.

Detailed description of finalize Functions

Finalize is a method located in the Object class. The access modifier of this method is protected. Because all classes are subclasses of objects, the user class can easily access this method. Because the finalize Function

The number does not automatically implement chained calls, so we must implement them manually. Therefore, the finalize function's last statement is usually super. finalize ().

In this way, we can implement finalize calling from bottom to top, that is, releasing our own resources first and then releasing the parent class resources. According to the Java language specification, JVM ensures that the finalize function is called

Previously, this object is not reachable, but the JVM does not guarantee that this function will be called. In addition, the finalize function can run at most once. Many Java beginners think this method is similar

In this function, many objects and resources are released. In fact, this is not a good method. There are three reasons:

First, in order to support the finalize function, GC requires a lot of additional work on the objects that overwrite the function.

Second, after the finalize operation is complete, the object may become reachable. GC also checks whether the object is reachable. Therefore, using finalize reduces the Running Performance of GC.

Third, the time for GC to call finalize is uncertain, so releasing resources in this way is also uncertain. In general, finalize is used to release very important resources that are not easily controlled. For example

For example, some I/O operations and data connections. The release of these resources is critical to the entire application. In this case, programmers should primarily manage (including releasing) these resources through the program itself

The finalize function, supplemented by the way resources are released, forms a double-insurance management mechanism, instead of relying solely on finalize to release resources.



How to answer the java garbage collection mechanism during the interview?

Java's garbage collection mechanism is the capability provided by the Java Virtual Machine. It is used to dynamically reclaim the memory space occupied by non-referenced objects in an irregular manner during idle time.
Note: Garbage collection is the memory space occupied by no referenced objects instead of the objects themselves. Many people will ask this question when they come to our company for an interview, more than 70% of the answers are intended to be recycled. In fact, this is incorrect.
System. gc ()
Runtime. getRuntime (). gc ()
When the above method is called, it is used to explicitly notify JVM that a garbage collection can be performed. However, the actual garbage collection mechanism is unpredictable at what time, this is the same principle as that of a preemptible thread when it works.

What causes jaVa Memory leakage?

Java Memory leakage

Generally, there are two scenarios for Memory leakage. For example, in C/C ++, the memory allocated in the heap is not released, all the methods that can access this memory are deleted (for example, the pointer is assigned a value again); the other is when the memory object is clearly not needed, the memory and its access method (reference) are still retained ). In the first case, the garbage collection mechanism has been introduced in Java, which has been well solved. Therefore, the memory leakage in Java mainly refers to the second case.
The concept may be too abstract. You can take a look at this example:

1 Vector v = new Vector (10 );
2 for (int I = 1; I <100; I ++ ){
3 Object o = new Object ();
4 v. add (o );
5 o = null;
6}

In this example, the reference v of the Vector Object and the reference o of the Object exist in the Code stack. In the For loop, we constantly generate new objects, add them to the Vector object, and then leave the o reference empty. The problem is, if GC occurs after the o reference is left empty, can the Object we created be recycled by GC? The answer is no. Because, when GC traces the reference in the Code stack, it will find the v reference, and continue to trace down, it will find that there is a reference pointing to the Object in the memory space that the v reference points. That is to say, although the o reference has been left empty, other references still exist in the Object, which can be accessed, so GC cannot release it. If the Object has no effect on the program after this loop, we think the Java program has a memory leakage.
Despite the memory leakage in C/C ++, Java Memory leakage causes little damage, except for a few cases where the program crashes, in most cases, the program can still run normally. However, when mobile devices have strict restrictions on memory and CPU, Java memory overflow may lead to low program efficiency and a large amount of unnecessary memory. This will cause the performance of the entire machine to deteriorate. In severe cases, it will also throw an OutOfMemoryError and cause the program to crash.

Generally, memory leakage is avoided.

In general, Java Memory leakage does not involve complex data structures. the lifecycle of a memory object exceeds the length of time required by the program. We sometimes call it "object free ".
For example:

1 public class FileSearch {
2
3 private byte [] content;
4 private File mFile;
5
6 public FileSearch (File file ){
7 mFile = file;
8}
9
10 public boolean hasString (String str ){
11 int size = getFileSize (mFile );
12 content = new byte [size];
13 loadFile (mFile, content );
14
15 String s = new String (content );
16 return s. contains (str );
17}
18}

In this Code, the FileSearch class has a function hasString to determine whether the document contains a specified string. The process is to first load the mFile into the memory and then judge. However, the problem here is that the content is declared as an instance variable rather than a local variable. Therefore, after this function is returned, the memory is still... the remaining full text>
 

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.