Java memory leak problem analysis

<! - Info --><!-- div> </ div> <div> <ul> <img src = "http://img1.e800.com.cn/service/temp/t12.jpg "/> <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 ();

return

)

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

  • del.icio.us
  • StumbleUpon
  • Digg
  • TwitThis
  • Mixx
  • Technorati
  • Facebook
  • NewsVine
  • Reddit
  • Google
  • LinkedIn
  • YahooMyWeb

Related Posts of Java memory leak problem analysis

  • Hibernate primary key strategy-sequence

    Today, the use of hibernate in the company encountered a troublesome problem, the use of hibernate when the primary key generation strategy set sequence, but always reported in the implementation could not get next sequence value of the error, then o ...

  • hibernate call stored procedure

    hibernate call stored procedure

  • hibernate using c3p0 connection pooling

    Private http://www.lifevv.com/tenyo/doc/20070605102040991.html c3p0 for open source's JDBC connection pool, with the release hibernate. This article describes how to use the hibernate configuration in c3p0. c3p0 connection pool configuration is v ...

  • Hibernate configuration parameters hibernate.hbm2ddl.auto

    Hibernate in the configuration file: <properties> <property name="hibernate.hbm2ddl.auto" value="create" /> </ properties> Parameter Description: validate load hibernate, the authentication to create a database t ...

  • Build flex + spring + blazeds + hibernate application

    Build flex + spring + blazeds + hibernate application First, set up the project blazeds 1, will blazeds.war extract to a directory, such as: myflex /; 2, set up java works were such as: MyFlex, in the orientation of selection create project from exis ...

  • Hibernate connection pool configuration

    Hibernate connection pool configuration <! - Jdbc -> <property name="connection.driver_class"> oracle.jdbc.driver.OracleDriver </ property> <property name="connection.url"> jdbc: oracle: thin: @ 10.203.14.132:15

  • hibernate generic generic DAO

    package org.lzpeng.dao; import java.io.Serializable; import java.util.List; import org.hibernate.Criteria; import org.hibernate.Query; import org.hibernate.criterion.Criterion; import org.springside.modules.orm.hibernate.Page; /** * * @version 2009-1-10 *

  • Struts2 + hibernate + spring problem user log in

    dao layer services layer action jsp <tr> <td align="center"> <b> user name: </ b> </ td> <td> <s: textfield name = "czyNumber" cssClass = "textstyle" theme = "simple" size = &q

  • Hibernate secondary cache

    Hibernate cache: 2-bit cache, also known as process-level cache or SessionFactory level cache, secondary cache can be shared by all of the session Cache configuration and the use of: Will echcache.xml (the document code in hibernate package directory ...

  • Hibernate's lazy strategy

    hibernate Lazy strategy can be used in: <class> tag, it can be true / false Tags can <PROPERTY> values true / false type of necessary tools to enhance <set> <list> can tag values true / false / extra <many-to-one> <on ...

blog comments powered by Disqus
Recent
Recent Entries
Tag Cloud
Random Entries