Sort out several common java memory leaks and solutions

Source: Internet
Author: User
Tags current time garbage collection memory usage requires stack trace system log

If you are not clear about the principle of java memory leakage, let's take a look at this article: how to prevent Java memory leakage.


1. How Java manages memory

To determine whether memory leakage exists in Java, we must first understand how Java manages memory. Java memory management is the issue of object allocation and release. In Java, memory allocation is done by the program, and the memory release is done by the Garbage Collection (GC). Programmers do not need to call functions to release the memory, however, it can only recycle the space occupied by objects that are useless and no longer referenced by other objects.

Java's memory garbage collection mechanism checks the reference chain from the main running objects of the program. After traversing it, it finds that the isolated objects that are not referenced are used as garbage collection. To release objects correctly, GC must monitor the running status of each object, including application, reference, reference, and assignment of objects. GC must monitor all objects. The object state is monitored to release objects more accurately and timely. The fundamental principle of releasing an object is that the object is no longer referenced.

In Java, GC recycles these useless objects, so programmers do not need to consider the memory leakage. Although we have several functions that can access GC, such as the System. GC () function that runs gc, according to the Java Language Specification definition, this function does not guarantee that the JVM garbage collector will certainly execute. Because different JVM implementers may use different algorithms to manage GC. Generally, the priority of GC Threads is low. There are also many policies for JVM to call GC. Some of them start to work when the memory usage reaches a certain level, some are scheduled, some are gentle execution of GC, and some are interrupted execution of GC. But in general, we don't need to care about this.

2. What is memory leakage in Java?

The main cause of memory leakage is that I forgot to release the memory I previously applied. If a reference to useless objects exists in the program, these objects will reside in the memory and consume the memory, because GC cannot be performed by the garbage collector to verify whether these objects are no longer needed. If an object is referenced, the object is defined as "valid activity" and will not be released. To determine that the memory occupied by an object will be recycled, make sure that the object will no longer be used. A typical practice is to set the object data member to null or remove the object from the set. However, when local variables are not needed, you do not need to explicitly set them to null because these references are automatically cleared when a method is executed.

In Java, memory leakage is the existence of some allocated objects. These objects have the following two features: first, these objects are referenced, that is, in a directed tree chart, tree branches can be connected to them. Second, these objects are useless, that is, they will not be used by programs in the future. If the objects meet these two conditions, these objects can be identified as memory leaks in Java. These objects are not recycled by GC, but occupy the memory.

Here we reference a common example. In the following code, we apply for an Object cyclically and put the applied Object into a Vector. If we only release the Object, however, because the Vector still references this object, this object cannot be recycled for GC. Therefore, if an object is added to a Vector, it must be deleted from the Vector. The simplest way is to set the Vector object to null.

Vector v = new Vector (10 );

For (int I = 1; I <100; I ++)

......{

Object o = new Object ();

V. add (o );

O = null;

} // At this time, all Object objects are not released because variable v references these objects.



In fact, these objects are useless, but when referenced, GC is powerless (in fact, GC thinks it is still useful), which is the most important cause of memory leakage. Another example is provided to illustrate the Java memory leakage. Assume that there is a log class Logger that provides a static log (String msg), and any other class can call Logger. log (message) to record the message content to the system Log file.

The Logger class has a static variable temp of type HashMap. Every time a log (message) is executed, first, write the message value to temp (with the current thread + current time as the key), and then delete the entry with the current thread and current time as the key from temp before exiting. Note: the current time is constantly changing. Therefore, the log cannot delete the entry written at the beginning of execution because the log deletes the entry before exiting. In this way, any string passed to log as a parameter cannot be recycled because it is referenced by the static variable temp of Logger. This object persistence is what we call Java memory leakage. In general, the main cause of memory leakage in memory management is the object reference that is retained but never used again.

III. Typical memory leaks

We know that memory leakage exists in Java, so let's take a look at several typical leaks and find out the causes and solutions for them.

3.1 Global set

It is common to have a variety of global data warehouses in large applications, such as a JNDI-tree or a session table. In these cases, you must pay attention to the size of the management repository. There must be a mechanism to remove unnecessary data from the repository.

There are usually many different solutions. The most common solution is to clear jobs that run cyclically. This job will verify the data in the repository and then clear all unnecessary data.

Another way to manage the repository is to use reverse link (referrer) to count. The set collects the number of reverse links for each entry in the set. This requires the reverse link to tell the set when the entry will exit. When the number of reverse links is zero, this element can be removed from the set.

3.2 Cache

Cache is a data structure used to quickly find the results of operations that have been executed. Therefore, if an operation requires more resources and will be used multiple times, it is usually used to cache the results of common input data operations, this allows you to use cached data when you call this operation next time. Cache is usually implemented dynamically. If the cache settings are incorrect and a large amount of cache is used, memory overflow may occur, therefore, we need to balance the memory used with the data retrieval speed.

A common solution is to use the java. lang. ref. SoftReference class to insist on caching objects. This method ensures that the reference of these objects can be released when the VM runs out of memory or requires more heaps.

3.3 Class loaders

The use of Java class loaders provides many opportunities for memory leakage. Generally, the class loaders have complex structures, because the class loaders are not only related to "regular" object references, but also internal references of objects. For example, data variables, methods, and types. This means that as long as there is a class loader for data variables, methods, various types and objects, the class loader will reside in JVM. Since the class loader can be associated with many classes and static data variables, a considerable amount of memory may leak.

4. How to detect and handle memory leaks

There are two steps to find out the cause of memory leakage: first, arrange experienced programmers to check and analyze the code to find out the location where the memory leakage occurs; the second is to use a dedicated memory leak test tool for testing.

The first step is to arrange for developers familiar with system business and development language tools to perform cross-query on the application code, try to find out the database connection statements in the code and the fault code such as the result set is not closed or code redundancy.

The second step is to detect Java memory leakage. Here we usually use some tools to check the memory leakage of Java programs. There are already several professional Java memory leak check tools on the market. Their basic working principles are similar. They are all through monitoring the application, release, and other actions of all objects when Java programs are running, collects, analyzes, and visualizes all memory management information. Based on this information, developers will determine whether the program has a memory leakage problem. These tools include Optimizeit Profiler, JProbe Profiler, JinSight, and Purify from Rational.

4.1 detect memory leakage
Here we will briefly introduce the process of using Optimizeit to check. Generally, after a memory leak occurs, the first step is to find out what data is leaked and what type of object is causing the leak.

Generally, the memory usage of a normal system is basically stable after it runs stably, and should not increase without limit. Similarly, there is a relatively stable upper limit on the number of objects used by any class, and it should not continue to grow. Based on this basic assumption, we constantly observe the memory size used during system operation and the number of instances. If the memory size continues to grow, it indicates that the system has memory leakage, if the number of instance objects of a specific class increases over time (that is, the so-called "growth rate"), it indicates that the instance of this class may be leaked.

On the other hand, there is usually a first sign of memory leakage: an OutOfMemoryError occurs in the application. In this case, some low-overhead tools are required to monitor and find memory leaks. Although OutOfMemoryError may also cause that the application is indeed using so much memory; in this case, you can increase the number of available JVMs or make some changes to the application, make it use less memory.

However, in many cases, OutOfMemoryError is a memory leak signal. One way to find out is to continuously monitor GC activities and determine whether memory usage increases over time. If so, memory leakage may occur. 1


4.2 How to handle memory leakage

Once you know that a memory leak occurs, you need more professional tools to find out why the leak occurs. The JVM won't tell you. These professional tools obtain information about the memory system from the JVM in two ways: JVMTI and byte code instrumentation ). Java Virtual Machine Tools Interface (JVMTI) and its predecessor Java Virtual Machine monitoring program Interface (JVMPI) it is a standardized interface for external tools to communicate with JVM and collect information from JVM. Bytecode technology refers to the technology that uses detectors to process bytecode to obtain information required by tools.

Optimizeit is a Borland product mainly used to assist in code optimization and fault diagnosis for Software Systems. Optimizeit Profiler is mainly used for memory leakage analysis. The heap view of Profiler is used to observe the memory size used by the system and the number of instances allocated for each class.

First, Profiler Analyzes the trend to find out which class objects are being leaked. After the system has been running for a long time, you can get four memory snapshots. Perform a comprehensive analysis on the four memory snapshots. If the memory usage of each snapshot is higher than the previous one, you can determine that the system has memory leakage, find out the classes that keep the number of instances increasing in the four snapshots. These classes can be initially identified as leaked. Through data collection and preliminary analysis, we can draw a preliminary conclusion: whether the system has memory leakage and which objects have been leaked (leaked ).

Next, let's see which other classes are associated with the leaked class objects. As mentioned above, memory leakage in Java is useless object persistence, simply put, a reference chain that should not have existed due to an encoding error (as a result, the referenced object cannot be released ), therefore, the task of memory leak analysis is to find out the redundant reference chain and find the cause of its formation. It is useful to view where objects are allocated. At the same time, it is not enough to know how they are associated with other objects (that is, which objects reference them), and information about where they are created is also useful.

Finally, we will further study individual objects to see how they are correlated. With the Profiler tool, the code in the application can be dynamically added at the time of allocation to create a stack trace. You can also dynamically track all objects in the system. These stack traces can be accumulated and analyzed in tools. For each leaked instance object, there must be a reference chain to reach the object starting from a traction object. When the pull object in the stack space is popped up from the stack, it will lose its traction capability and become a non-traction object. Therefore, after a long period of operation, the leaked objects are basically pulled by the static variables of the class.


All in all, although Java has the ability to automatically recycle and manage memory, the memory leakage cannot be ignored. It is often an important factor that damages system stability.

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.