Java memory leaks

Source: Internet
Author: User
Tags close close object object

The previous article mentioned Java garbage collection, today talk about the memory leaks in Java.

First, we discuss the Java memory Management mechanism:

In Java programs, we typically use new to allocate memory to objects that are on the heap.

public class Test {public    static void main (String args[]) {        Object object1 = new Object ();//obj1        Obje CT object2 = new Object ();//obj2        object2 = object1;      }}

In the above code, two objects Obj1 and Obj2 are created, each of which takes up a portion of memory, however, two objects reference variables Object1 and object2 that point to Obj1 's block of memory, and OBJ2 is unreachable due to the Java garbage collection target, is to clean up the memory of the unreachable objects, and the fundamental principle of releasing the object is that the object will no longer be used (that is, no reference variable points to the memory space occupied by the object), so obj2 can be cleaned.

Here are a few examples to illustrate the memory leaks in Java:

memory leak definition: When some objects are no longer used by the application, but because they are still referenced, the garbage collector cannot release (remove, remove) them.

1. Long life-cycle objects hold short life-cycle references, and memory leaks are likely to occur

 Public class Test {    Object object;      Public void Test () {        new  Object ();         // ... Other code     }}

In this example, after the test method in the test class is finished, the memory used by the created object is not immediately considered to be free, and the garbage collection is already in the strictest sense. There are two workarounds: at the end of the test method, display the object ==null to a flag that can be recycled, and object as a local variable inside the test method.

2. Static collection classes like HashMap, vectors, etc. are most prone to memory leaks, and the lifetime of these static variables is consistent with the application, and all object objects cannot be freed, as they will always be used by vectors and so on.

Static vector v = new vector ();
for (int i = 1; i<100; i++)
{
Object o = new Object ();
V.add (o);
o = null;
}

In this example, there is a reference to the vector object in the code stack with reference to the V and object o. In the For loop, we constantly generate new objects, add them to the Vector object, and then empty the O reference. The question is, if a GC occurs when the O reference is empty, can we create an object that is recycled by GC? The answer is in the negative. Because, when the GC traces a reference in the code stack, it discovers a V reference, and continues to trace, it finds that the memory space pointed to by the V reference has a reference to the object. This means that although the O reference is already empty, there are still other references to object objects that can be accessed, so the GC cannot release it. If after this loop the object object has no effect on the program, we assume that the Java program has a memory leak.

3. The remove () method does not work when the object properties in the collection have been modified.

 Public Static voidMain (string[] args) {Set<Person> set =NewHashset<person>(); Person P1=NewPerson ("Tang priest", "Pwd1", 25); Person P2=NewPerson ("Monkey King", "Pwd2", 26); Person P3=NewPerson ("Pig", "pwd3", 27);     Set.add (p1);     Set.add (p2);     Set.add (p3); System.out.println ("A total of:" +set.size () + "Elements!");//results: Total: 3 elements!P3.setage (2);//modifies the age of P3, at which point the P3 element corresponds to a hashcode value that changesSet.remove (p3);//The Remove does not drop at this time, causing a memory leakSet.add (p3);//re-add, incredibly add successSystem.out.println ("A total of:" +set.size () + "Elements!");//results: Total: 4 Elements!     for(person Person:set) {System.out.println (person); } }    

4. Various connections, database connections, network connections, IO connections, etc. do not show call Close closed, not be garbage collected caused memory leaks, for resultset and statement objects can not be explicitly recycled, but connection must be explicitly recycled, Because connection is not automatically recycled at any time, and connection once reclaimed, Resultset and statement objects are immediately null;

5. References to internal classes and external modules;

6. When the singleton object is initialized, it will exist in the entire life cycle of the JVM (in the way of a static variable), and if the Singleton object holds a reference to an external object, the external object will not be properly reclaimed by the JVM, resulting in a memory leak;

7. The use of listeners can also cause memory leaks if the object is freed without a corresponding delete listener.

Principles of memory leak resolution:

1. Minimize the use of static variables, the life cycle of class static variables and class synchronization.

2. Before declaring an object reference, clear the valid scope of the memory object, minimize the scope of the object, and rewrite the member variable of the class as a local variable within the method;

3. Reduce the long life cycle of objects holding short life cycle references;

4. using StringBuilder and StringBuffer for string connections, Sting and StringBuilder, and StringBuffer can all represent strings, Where a string string represents an immutable string, and the latter represents a mutable string.  If you use multiple string objects to concatenate strings, you can produce a large number of temporary strings at run time, which are stored in memory and cause program performance to degrade.

5. To manually set null values for objects that do not need to be used, we should promptly mark useless objects as objects that can be cleaned up, regardless of when the GC begins to clean up.

6. Various connections (database connection, network connection, IO Connection) operation, be sure to show call close close.

Java memory leak

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.