Java memory leak problem analysis

<! - Info --><!-- div> </ div> <div> <ul> <img src = " "/> <p> <a href=""> information first time </ a> </ p> </ ul> <ul> <li> <a href="" title=""> information first time" / a> article </ li> <li> <p> <a href="" title=""> Hewlett-Packard released new software </ a> </ p> <p> <a href = "" title = "" "Hewlett-Packard released new software </ a> </ p> </ li> <li> concept of situation calls for the promotion of the development process of the software services industry in promoting the concept of situation calls for the development process of the software services industry in promoting the concept of situation calls for the software services industry the process of development </ li> </ ul> <ul> <p> <a href=""> personal page </ a> </ p> <p> <a href=""> send a message </ a> </ p> </ ul> </ div> <div> </ div - ><!-- comment ->

A lot of people talking about the memory leak problem, of course, for c / c + +, this should be a long-standing problems, but many more Java staff also need to discuss this issue, I write a summary here, in the hope we have certain reference Value .

Generous concept of memory leaks

1.c / c + + programmer self-rule of memory, Java memory is automatically collected by the GC.

Although I am not very familiar with C + +, but this should not be guilty of an error bar of common sense.

2. What is a memory leak?

Memory leak is present in the system can not recover the memory, may lead to memory or system crashes.

In the C / C + + does not release memory allocated in the case of memory leaks.

3.Java a memory leak

We must first admit that this can only be followed by discussion. Although the Java memory leak exists, but it is basically not very concerned about it, and extraordinary is that the code itself does not pay attention to the right not to care about it any more.

Java, of course, refers to the memory leak: the existence of useless garbage collector, but the object can not be recovered. And even if there is memory leak problem, not necessarily be shown.

4.Java pass the value of the parameters are.

For the basic types, we basically have no objection, but for reference types, we can not object to this.

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 programmer need to apply keyword new memory space for each object (except for basic types), all of the objects in the heap (Heap) in the allocated space. In addition, the release of the object by the GC decisions and implementation. In Java, the memory allocation is done by the program, while the memory is a GC to complete the release, this two-line method of revenue and expenditure is indeed simplify the programmer's work. At the same time, it also increased the JVM's work. This is the Java program runs slower one of the reasons. Because, GC in order to be able to correct the release of the object, GC will have to 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 order to better understand the GC works, we can consider a directed graph object vertices, people will consider the relationship between graph directed edges, there are those who point to the edges have been cited from the reference object. In addition, each thread object can be used as the starting vertex of a graph, for example, most programs started from the main process, then the main process of the plan is to start a root vertex tree. In this directed graph, the root vertex of the object is valid up to an object, GC will not recover these objects. If an object (connected sub-graph) and the root vertex is not up to (note that the photo shows a directed graph), then we think that this (these) objects are no longer referenced and can be recycled GC.

Below, we give an example of how to use a directed graph that memory management. For the program every moment, we have a directed graph that JVM memory allocation. Below at right, that is on the left to run to the first six rows of the diagram.

Java memory leak problem analysis

Java using the directed graph approach to memory management, can remove reference to the cycle of issues, such as three objects, each reference, as long as they and the root process does not reach, then the GC is also can be recycled them. The advantage of this approach is to manage the memory, high precision, but less efficient. Another commonly used technique is to use the memory management counters, such as the COM model uses the counter managed components, compared with a directed graph, precision, OK low (difficult to deal with circular reference issues), but the implementation of high efficiency.

Java memory leaks

JVM collection algorithm is very complicated, and I do not know how they achieved, but I only know that they want to achieve is this: for the object is not referenced can be recycled. So you want to create memory leaks should be done:

Holds an object reference to the useless!

Do not think that this is very easy to do, since useless, how can you still hold a reference to it? Since you still hold it, how it would be useless then?

I really can not think of a more than that classic example of the stack, and so on I would like to quote someone else's example, the following examples do I have in mind is that the books have seen, of course, if there is no saw in the book, it may over time I myself think that, but when I say I think no one will believe it.

public class Stack (

private Object [] elements = new Object [10];

private int size = 0;

public void push (Object e) (

ensureCapacity ();

elements [size + +] = e;


public Object pop () (

if (size == 0)

throw new EmptyStackException ();

return elements [- size];


private void ensureCapacity () (

if (elements.length == size) (

Object [] oldElements = elements;

elements = new Object [2 * elements.length +1];

System.arraycopy (oldElements, 0, elements, 0, size);




The above principles should be very simple, if the addition of 10 elements in the stack, and then all the pop-up to, while the stack is empty, there is no what we want, but it is an object can not be recovered, this is consistent with a memory leak of the two conditions: useless, can not be recovered.

But is that there is such a thing does not necessarily lead to what consequences, if the stack used is relatively small, thus wasting a few K of memory only, since we are all on the G memory, and where there will be any effect, again this thing would soon be recovered, and have anything to do. The following look at two examples.

Example 1

public class Bad (

public static Stack s = Stack ();

static (

s.push (new Object ());

s.pop (); / / Here, there is a memory leak occurs

s.push (new Object ()); / / The above object can be recovered, and so therefore self-healing of the



Because it is static, there has been to the program out, but we can also see that it has self-healing function, that is if you Stack up to 100 objects, then it was only a maximum of 100 objects can not be recycled In fact, this should be very easy to understand, Stack references within the holder 100, the worst case is they are useless, because once we put a new spirit, the previous reference to disappear naturally!

Example 2

public class NotTooBad (

public void doSomething () (

Stack s = new Stack ();

s.push (new Object ());

/ / other code

s.pop ();// Here again, the object can not lead to recovery of memory leak.

) / / Exit the method, s automatically null and void, s can be recycled, Stack-house without reference to the natural, so

/ / Here you can heal, but can say that this method there is no memory leak problem, but come later

/ / To the GC, because when it is closed, the external is not open, we can say the above code to 99.9999% of the

/ / Will not cause any impact is, of course, you write such a code does not have any bad effects, but

/ / Code that can be said that garbage! No contradiction, and I add an empty inside for loop would not have

/ / What is too big an impact it, you will do this?


The above two examples are nothing but a minor, but C / C + + Memory leak is not Bad, but rather Worst of. If one does not recall that they will never recover, frequent calls this method not to run out of memory! Because of Java there are self-healing features (from my own name, not patent), so memory leaks in Java are virtually can be ignored, but people know not broken the.

I do not know were innocent! Java memory leak exists, but not exaggerated. If you are not very familiar with Java, you simply do not care about this, I said that you accidentally write a memory leak case as you like in the probability of 10.001 million small joke, but in fact should be a smaller number of more!

And even if you are fortunate enough to write such a code, and hit the jackpot! Are basically a pack of washing powder, will not let you make a fortune on the system does not have any major impact.

Unfounded cases

1. Have nothing to say type

Object obj = new Object ();

obj = null;

/ / This completely superfluous, because out of scope, the object reference automatically disappear

/ / Do not appear in your program this statement, there is nothing wrong, but it is unsightly

2. Thinking wrong type

void func (Object o) (

o = new Object ();



When we know Java parameters are passed by value, they will know what's true the above method is applied to an object and then threw GC. Because it is passed by value, where o is a copy of call time, will not be recovered? Is not copying do, exit the method, we've got nothing, how this object will remain a living.

3. As far as possible to avoid the type

class A (

B b = new B (this);


class B (

A a;

B (A a) (this.a = a;)


The existence of mutual reference, may lead to an island phenomenon, but this does not cause memory leaks, but I think this will reduce the efficiency of GC on intelligence from my point of view, I think this situation is difficult to determine how than the average recovery! GC smarter than I am, of course, but it should also move a little brain bar.

In the component prior to submission to the integration phase, each developer must carry out the performance of their unit test components. Unit tests focus solely on the traditional function of the expense of performance.

During testing at the unit, performance unit testing implies the need for tools to analyze with the following components:

Memory profiler

Code profiler

Coverage profiler

Memory profiler in use cases and use cases before the start of the end of the garbage collector to run and record a snapshot of the heap. From these data, we can see the impact of memory use cases and the use case in memory left a list of specific objects. Developers need to check to make sure those objects in use cases after the implementation of those objects should be retained in memory. When the use case is completed, if the object is inadvertently left in the heap, then this is the Java memory leaks, and we, as free objects, sometimes also called legacy object reference.

The next need to find a memory problem known as the target circle. During the implementation of the use case, the recorded information on fine-grained sampling of the heap, combining to create and delete the number, indicating the object is created and deleted frequently. If the object is to quickly create and delete, it will be brought to the JVM great pressure. Each is created and deleted objects can only be collected by the garbage collection and recycling targets significantly increased the frequency of garbage collection. This situation usually occurs in a loop or nested loops to create an object inside the case.

Let us look at the following code:

for (int i = 0; i

for (int j = 0; j

int threshold = system.getThreshold ();

if (object [i]. getThing () - object2 [j]. getOtherThing ()> threshold) (

/ / Do something




In this case, the external loop through the object of all the items, and each project object2 traverse all the items. If the object contains 1000 projects and object2 also includes 1,000 items, it is defined in the code inside the loop will be executed 1000 * 1000, or a million times. In this code, the threshold variable each time the inner loop at run time (when the object reference goes out of scope when the scope of the object will be destroyed) has been allocated and destroyed. Memory profiler, if you saw this code, you will see 1 million threshold instances are created and destroyed.

Code should be rewritten using the following methods to eliminate this situation:

int threshold = system.getThreshold ();

int threshold = system.getThreshold ();

for (int j = 0; j

if (object [i]. getThing () - object2 [j]. getOtherThing ()> threshold) (

/ / Do something




Now, with one million cycles, the threshold variable is assigned only once. The impact of the variable threshold becomes negligible importance.

Web-based applications, we often see a circle on the target scene is created in the context of the request object. In the single-use situations, this is not a problem, but when a user loads a significant increase, this problem quickly became apparent. You have to make a decision, this object is created for each request needs to be based, or if once it is created, it can be buffered to a request by the subsequent reuse. If the answer to this question is the latter, then you can eliminate the cycle of use of the object. Figure 1 shows the cycle occurs when the object heap view.

eclipse has set the jvm startup parameters from the size, because the eclipse also need to run their own jvm, so eclipse.ini where size is not set jvm to run a particular program, used when jvm size, and specific programs that run jvm size.

So how can we set up a program the size of the jvm does (of course, the console is running, then this problem would not exist, such as: java-Xms256m-Xmx1024m classname, so can the size of the current program to set the jvm)?

Because the eclipse of a program where the default jvm is configured to:-Xms8m-Xmx128m, so we deal with relatively large consumption of memory needed to manually adjust the look so as not to overflow the memory. A specific set methods are:

Has been selected to run the class, click on the menu 'Run-> Run Configurations ...', select (x) = Argument tab under the vm arguments box type-Xmx512m, save the running of the ok.

I often deal with large floating-point matrix, so I use the-Xmx1024m

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


  • Java program in the "memory leak" problem 2010-07-20

    Transfer from: Soar Abstract: Java's memory management system from the beginning with a discussion of the Java process memory leak cause of the problem, citing a typical memory leak prob

  • Class loader - the memory leak problem of a 2010-07-29

    About websphere console to restart the application, rather than restart the websphere, this time a static class can not be recovered, resulting in some classes can not be destroyed, occupied by the memory, but this memory can not be reused, can be sa

  • Browser memory leak problem tracking and resolution 2010-09-20

    Browser memory leak problem tracking and resolution prevailed before stored in Ajax, browser memory leaks is not a big problem, because they were all jump through the page and Shuaxin Laijinxingyu Jiaohu server side and they are now not the same, man

  • Java memory leak problem analysis (change) 2010-03-28

    People talking about memory leaks, of course, for c / c + +, this should be the long-standing problems, but many more Java staff also need to discuss this issue, I write a summary here, we want to have some reference value. Generous concept of memory

  • Class loader - the memory leak problem of 2 2010-07-29

    Serious warning: If there is any application other than from a reference cited by the J2EE application itself class loader loads the class and class instance object, then ClassLoader class loader memory leak problem arises. ClassLoader class loader m

  • Using JAX-WS Annotated Services from Java + JAXB release access to web service 2010-06-03

    CXF has a variety of data binding methods, such as: Aegis Databinding, JAXB, MTOM Attachments. Which JAXB (JavaTM Architecture for XML Binding) is the default data binding approach. JAXB is an example of automatic mapping XML and Java development int

  • Notes on ResultSet memory overflow problem of OutOfMemory 2010-12-29

    ResultSet memory overflow problem of OutOfMemory Error message is as follows: jdbc oracle in operation when the huge amount of data returned by the ResultSet get all the data out of memory overflow Treatment: Cause of the error is using a scrollable

  • Software: software is to rule the world 2011-08-23

    Software: software is to rule the world blackhat Posted at 17:18 on August 22, 2011 Monday Printer-friendly Email story Department overtime late into the night from the programmer Last week, the world's largest PC maker Hewlett-Packard announced that

  • When installing MySQL can not start service (could not start the service) 2010-06-17

    Reproduced in BA% AE% D3% EA008/blog/item/4d33f8a87b1094f71e17a2df.html When you install mysql, to the last step, implementation, in the start service, the following error: Could not start the service generally occurs because ma

iOS 开发

Android 开发

Python 开发



PHP 开发

Ruby 开发






Javascript 开发

.NET 开发



Copyright (C), All Rights Reserved. 版权所有 闽ICP备15018612号

processed in 0.314 (s). 10 q(s)