Java memory leak analysis and solution of

July 24, 2009 Friday, 00:17

Java memory leak that every Java programmer will be the problems encountered, the program is running in the local all normal, but there will be deployed to remote memory, unlimited growth, the final system paralyzed, then how fastest and best testing process stability, prevent the system from collapse, the authors use their own personal experience to share with you the User to solve these problems.

As the Internet, one of the most popular programming languages, Java is now very popular. Our web application on the main use of Java language development, in general be divided into client, server and database at three levels. Into the testing process, we found a program module system memory and CPU resource consumption increased dramatically, sustained growth until the appearance of java.lang.OutOfMemoryError. After analysis of Java memory leak is a major factor in undermining the system. Here with us to share our experience in the development process in Java memory leak detection and processing of the settlement process.

1. Java is how to manage memory

In order to determine whether there are memory leaks in Java, we first have to understand Java is how to manage memory. Java memory management is the allocation and release of objects. In Java, the memory allocation is done by the program, while the release of the memory by the garbage collector (Garbage Collection, GC) completed, programmers do not need to by calling the function to release the memory, but it is useless and can only be recovered are no longer referenced by other objects the space occupied by those objects.

Java memory garbage collection mechanism is the main operating target from the program to start checking references chain, when the traversal is not referenced again and found an isolated object for garbage collection. GC To be able to correct the release of an object, you must monitor the operational status of each object, including the object's application, references, cited, and assignment, etc., GC needs to be monitored. Monitoring object state is to be more accurate, and timely release of the object, while the release of the object's fundamental principle is that the object is no longer referenced.

In Java, these useless objects by the GC is responsible for recovery, so programmers need not consider this part of the memory leak. Although we have several functions can access the GC, for example, run the GC function System.gc (), but the Java language specification according to the definition of the function is not guaranteed JVM garbage collector will definitely be implemented. Because different JVM implementation may use different algorithms for management of GC. GC thread is usually a low priority level. JVM called GC strategy There are many, and some memory usage reaches a certain degree, GC to start work, there are regularly performed, and some flat implementation of the GC, either interrupt-style implementation of the GC. But generally speaking, we do not care about these.

2. What is a memory leak in Java

The main reason leading to memory leaks is that previously applied for and forget to release memory space. If the program is in reference to the existence of useless objects, these objects will be the presence of memory, the memory consumption, because they can not let garbage collector GC verify whether these objects no longer needed. If there is a reference to an object, this object is defined as "effective activities" and would not be released. To determine the share of the memory objects will be recovered, we will be sure to confirm that the object will no longer be used. A typical approach is to set to null or the object data members to remove the object from the collection. However, when local variables do not need to, without a clear set to null, because a method is finished, these references will automatically be removed.

In Java, the memory leaks that have been allocated, there are some objects, these objects have the following two characteristics, first of all, these objects are being referenced, that is a directed tree, there is a branch pathway could possibly be linked; followed by , these objects are useless, that program will be no further use of these objects. If the object is to satisfy these two conditions, these objects can be judged to be in the Java memory leaks, these objects can not be recovered by GC, but it does take up memory.

Here one can often see the example cited in the following code, the loop for Object object, and the requested object into a Vector, if only the release of the object itself, but because Vector is still reference to the object, so the object of GC is not recycling. Therefore, if the object added to the Vector, you must also remove from the Vector, the simplest way is to Vector object is set 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 point, all of Object objects have not been released because the variable v refer to these objects.
In fact these objects is useless, but it has also been cited, GC can not do anything (in fact, thought it useful to GC), memory leak that led to the most important reason. To cite another example to illustrate the Java memory leak. Suppose there is a log class Logger, it provides a static log (String msg), any other class can call Logger.Log (message) to the contents of the message recorded in the system log file.

Logger class has a static type HashMap variable temp, each time in the implementation of log (message), it also first to write temp in the value of the message (in the current thread + the current time as the key), before exiting again from temp will be in the current thread and the current time is key to delete the entry. Note that the current time is constantly changing, so delete the log entries before exiting the implementation of the operation does not remove the implementation of the beginning of written entries. In this way, any one of a string as a parameter passed to log eventually caused by the Logger's static variable temp reference, but can not be recovered, such an object to maintain what we call Java memory leak. In general, memory management of the memory leak generated main reasons: to retain, though it will never again use the object reference.

3. Several typical memory leak

We know that in Java, there is indeed a memory leak, then let us look at several typical leakage, and identify their causes and solutions occur.

3.1 The global collection of applications exist in a large variety of global data warehouse is very common, such as a JNDI-tree or a session table. In these cases, management must pay attention to the size of the repository. There must be some mechanism to remove from the repository of data is no longer needed.

Usually there are many different forms of settlement, the most commonly used is a cycle of operation clean-up operations. This operation will verify that the data warehouse and then remove all the unwanted data.

Another way to manage the repository is to use the reverse link (referrer) count. Is responsible for statistics collection and then set the reverse link for each entry number. This requires the collection of backlinks to tell when it will withdraw from the entrance. When the number of zero, the element can be removed from the collection.

3.2 Cache Cache a method used to quickly find the results of operations have been implemented over the data structure. Therefore, if an operation implementation will require more resources and will be used many times, common practice is to input data commonly used to cache the results of operations for the next call to the operation using the cache data. Caches are usually implemented in a dynamic manner, if the cache settings are not correct and extensive use of cache memory overflow occurs, then the consequences, so the need to use the memory capacity and speed of retrieval of data to be balanced.

Common solution was to insist on the use of java.lang.ref.SoftReference class objects into the cache. This method ensures that when the virtual machine runs out of memory or the need for more heap, they can release the object.

3.3 Class Loader
Java class loader used to provide many opportunities for memory leaks. General class loader has a complex structure, because the class loader is not just with the "regular" object reference to the relevant, but also within the reference and object related. Such as data variables, methods, and a variety of categories. This means that as long as the existence of data variables, methods, a variety of classes and objects of class loader, then the class loader will reside in the JVM. Since the class loader can be associated with many classes, but also can be associated with static data variables, then a lot of memory leak may occur.

4. How to detect and deal with memory leaks <br /> How do I find memory leaks caused by the reasons in general there are two steps: first is to arrange experienced programmers to the code walk-through and analyzed to identify the location of the memory leak occurred; The second is to use a dedicated memory leak testing tools for testing.

The first step in the code walk-through of the work, you can arrange for the system development language tools for business and developers are more familiar with the application of the code cross-walk-as far as possible to find the code that exist in the database connection statements and result set is not closed , code redundancy fault code.

The second step is to test Java memory leak. Here we usually use some tools to check the Java process memory leak problem. There have been several checks on the market of professional tools for Java memory leaks, and their basic working principle is similar, is by monitoring the Java program runs, all objects of the application, the release of their movements, will all the information memory management statistics, analysis, visualization. Developer will process this information to determine whether there is a memory leak. These tools include Optimizeit Profiler, JProbe Profiler, JinSight, Rational's Purify and so on.

4.1 Detection of the presence of memory leaks Here we will briefly introduce our use Optimizeit inspection process. Usually known memory leak occurs after the first step is to figure out what data and which leaked object of the class caused a leak.

In general, a normal operation of the system in its stable of its memory footprint is basically stable, and should not be unlimited growth. Similarly, for any use of the object of a class also has a relatively stable number of ceiling should not be a continuous growth. According to this basic assumption, we continue to observe the system operation the size of memory used and the number of instances, if the memory size of the sustained growth of the system is illustrated in a memory leak, if a particular instance of an object class number with time The growth (so-called "growth"), then there may be an instance of this class leakage.

The other hand, usually occurs the first indication of memory leak is: in the application appeared OutOfMemoryError. In this case, the need to use some lower-cost tools to monitor and search for memory leaks. Although the OutOfMemoryError is also possible the application does is to use so much memory; In this case, you can increase the amount of JVM heap available, or some kind of application changes, so that it uses less memory.

However, in many cases, OutOfMemoryError is a memory leak signal. A kind of identification method is to continuously monitor the activities of GC to determine whether the memory usage increases over time. If so, a memory leak may occur.

4.2 The method of dealing with memory leaks occurred, once know the exact memory leak, you need a more professional tools to identify why the leak. JVM itself will not tell you. These professional tools obtained from the JVM memory system means there are basically two kinds of information: JVMTI and byte-code (byte code instrumentation). Java Virtual Machine Tools Interface (Java Virtual Machine Tools Interface, JVMTI) and its predecessor, Java Virtual Machine Monitoring Program Interface (Java Virtual Machine Profiling Interface, JVMPI) is an external tool to communicate with the JVM and the JVM to collect information from the standardization of interfaces. Byte-code technology is the use of detectors to obtain the tools for dealing with byte-code the required information technology.

Optimizeit is Borland's products, mainly used to help the software system code optimization and fault diagnosis, which Optimizeit Profiler is mainly used for memory leak analysis. Profiler heap view of system operation is used to observe the use of memory size and distribution of all instances of a class number of the.

First of all, Profiler will conduct trend analysis, find out which class an object in the leak. System operation can be long after the memory snapshot 4. Of these four memory snapshot of a comprehensive analysis, if every time a snapshot of memory usage than the last time to grow, you can identify a memory leak in the system to identify the four instances of the snapshot has maintained growth in the number of classes, These classes can initially be identified as there is leakage. Through data collection and preliminary analysis of preliminary conclusions can be drawn: the system has memory leaks and which objects exist leak (leaked).

Next, take a look at what other classes and leakage associated with the class of the object. Had already talked about memory leaks in Java is useless to stay in, simply to say that is because the coding error led to the existence of a reference should not have been the existence of chains (and thus led to the referenced object can not be released), so that the memory Leakage Analysis of the task is to find a reference to this extra chain and find the reasons for its formation. View the object is assigned to where it is very useful. At the same time only knows how they are associated with other objects (ie, an object which refers to them) is not enough, on where they are created information is also useful.

Finally, the further study of a single object, to see how they are interconnected. With Profiler tool, in the application code can be dynamically added in the allocation of time to create a stack trace. There are also all objects in the system can be dynamically allocated stack trace. The stack trace can be carried out in the tool accumulated and analyzed. For each instance of a leaked object, there must be a departure from a traction object arrived at the object reference chain. Traction in the stack space objects removed from the stack after the pop-up lost its traction ability to become the object of non-traction. Thus, in the long run after being leaked objects are basically used as a class static variable traction traction objects.
All in all, Java although the automatic recovery of the memory management functions, but the memory leak can not be ignored, it is often an important factor in undermining the system stability.

************************************************** ************************************************** ********

分类:Java 时间:2010-03-29 人气:331
分享到:
blog comments powered by Disqus

相关文章

  • Garbage collection mechanism 2010-04-14

    In the past year, had their own little concerned about the Java technology, the latest to see, do not let your behind the times! Google queries in a moment, the article on the garbage collection mechanism, integrated a bit, as follows: 1. Tags - Clea

  • A comprehensive analysis of Java's garbage collection mechanism 2010-01-29

    Introduction Java run-time heap is a data area, the class instance (object) from which the allocation of space. Java Virtual Machine (JVM) heap storage of the applications that are running all the objects created, these objects through the new, newar

  • Java's garbage collection mechanism 2010-06-24

    The full text: http://topic.csdn.net/u/20091211/12/c79a9293-fdd5-4f81-b18f-a4a29c8d9be2.html Study: yang677888 (from CSDN) Introduction Java run-time heap is a data area, the class instance (object) from distribution space. Java Virtual Machine (JVM)

  • Java's garbage collection summary and to learn Java garbage collection mechanism for experience 2008-06-09

    Memory is a scarce resource, even if memory, a money one! If the improper use of programming, then the memory will run out of big. First, understand Java's automatic garbage collection garbage collection is one of the major characteristics of Java la

  • Comprehensive analysis of Java's garbage collection mechanism 2010-04-19

    Java heap is a run-time data area, the class instance (object) from distribution space. Java Virtual Machine (JVM) heap storage of the applications are running all the objects created, these objects through the new, newarray, anewarray and multianewa

  • Java garbage collection mechanism and the tuning 2010-03-29

    1.JVM an overview of the gc or gc garbage collection mechanism is no longer in use jvm for the release of those occupied by the object of memory. java language does not require the jvm has gc, there is no provision gc how they work. However, commonly

  • On Java, the garbage collection mechanism 2010-07-01

    1. Garbage collection is a dynamic storage management technology, which automatically releases the object reference is no longer procedure, according to a particular garbage collection algorithm to auto-recovery function of resources. When an object

  • JVM garbage collection mechanism and GC Adjustment 2010-03-29

    JVM garbage collection mechanism and GC Adjustment 1, GC Summary: Knowledge of why the JVM heap, said first JVM heap? JVM is a Java object heap space for activities, procedures, objects in the class from which the allocation of space, its stores are

  • Android's garbage collection mechanism (android refbase class (sp wp)) 2010-08-09

    The implementation of sp and wp ~ ~ Personally feel that the sp and wp is actually android for c + + implementation of automatic garbage collection mechanism , specific to the internal implementation, sp and wp is really just an implementation of gar

  • php garbage collection mechanism to prevent memory overflow 2010-07-16

    Every language has its own automatic garbage collection, so that programmers need not overly concerned by the program memory allocation, but in OOP, some object needs to explicitly destroyed; prevent program execution memory overflow. 1, PHP garbage

iOS 开发

Android 开发

Python 开发

JAVA 开发

开发语言

PHP 开发

Ruby 开发

搜索

前端开发

数据库

开发工具

开放平台

Javascript 开发

.NET 开发

云计算

服务器

Copyright (C) codeweblog.com, All Rights Reserved.

CodeWeblog.com 版权所有 黔ICP备15002463号-1

processed in 0.837 (s). 12 q(s)