Java memory leak analysis and solution of

sponsored links
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.

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

  • StumbleUpon
  • Digg
  • TwitThis
  • Mixx
  • Technorati
  • Facebook
  • NewsVine
  • Reddit
  • Google
  • LinkedIn
  • YahooMyWeb

Related Posts of Java memory leak analysis and solution of

  • Depth understanding of Javascript closure (closure)

    Recently, online access to a lot of Javascript closure (closure) of relevant information and writing are very academic and professional. For beginners to understand let alone closure, and even the language describing it is very difficult to understan ...

  • J2EEer Learn Ruby

    Ruby has long heard of the development of efficient and accurate is to use Ruby on Rails to develop WEB applications very convenient. While J2EE has a lot of very good Opensource framework, automatic code generation tools, can greatly enhance the developm

  • ruby MBARI large patches Performance Evaluation Report

    Before JavaEye news ruby memory leak culprit - the specter of a detailed analysis of the current pointer Ruby official version (MRI version) causes memory leaks. Brent Roman today issued a Super patch , Which contains 6 patch file to resolve the Ruby ...

  • Struts Spring Hibernate test Noodles

    Hibernate working principle and why to use? Principle: 1. To read and parse configuration file 2. Read and analytic mapping information, create a SessionFactory 3. Open Sesssion 4. Create Affairs transation 5. Persistence operation 6. Submitted Services 7

  • js examples of common events

    <html> <head> <script type="text/javascript"> / / Which mouse button is clicked function whichButton1 (event) ( if (event.button == 2) ( alert ( "You clicked the right mouse button!") ) else ( alert ( "You c ...

  • SUI-JavaScript rich UI library integration solution

    Introduction: SUI is not a class implementation of the UI, nor is it a standard set of UI markup language, it is just to help the existing UI frameworks (such as Ext, YUI like) to mark the way to the statement and the creation of UI. The names of these ta

  • Java Programmer job

    Personal Resume Tertiary qualifications (09 session) Political outlook of members of 22 professional software technology age - NIIT Contact us 13138628171 Email -------------------------------------------------- -------------------- ...

  • J2EE Architect road

    J2EE Architect road Looking casual, working into the fifth year, the discovery came from the Java programmer to architect J2EE course. Found that computer to install a wide range of J2EE tools: JBuilder, WSAD, Eclipse, Rose, Together, Weblogic, Jtest, Opt

  • Some interview questions java

    The first is the company give you a chance to meet, it is necessary to know to meet from time to equal the interview, and have a lot of companies to see you at the first time will give you a ready point of doing something trivial, these questions, althoug

  • In the servlet use Bean

    According to Sun's definition, JavaBean is a reusable software components. In fact JavaBean is a Java class, through the package into a property and methods of treatment of a function or a business object, referred to as bean. Because JavaBean is ...

blog comments powered by Disqus
Recent Entries
Tag Cloud
Random Entries