Policy When assign an object to a variable, then a reference to the object is created, if the reference is not destroyed, the object can not be released by Garbage Collector. ie. SomeClass a = new SomeClass(); .... static SomeClass b = a; .... if 'b = null' or 'b = other_obj' is not called, the object can't be released.
Java Garbage Collector will release object out of its scope
Local Objects void fun() { SomeClass obj1 = new SomeClass(); .... if (true) { SomeClass obj2 = new SomeClass(); } //obj2 will be released automatically at the end of 'if' block without calling obj2 = null explicitly .... } //obj1 will be released automatically at the end of function without calling obj21= null explicitly
Class Fields class MyClass { private SomeClass m_obj; public MyClass() { m_obj = new SomeClass(); } }
MyClass obj = new MyClass(); .... obj = null; //The m_obj of MyClass will be released here. you need not to release it with 'm_obj = null' in finalize() method of MyClass.
Common Memory Leak in Java
Unknown or unwanted object references These objects are no longer needed, but the garbage collector can not reclaim the memory because another object still refers
to it.
Long-living (static) objects These objects stay in
the memory for the application's full lifetime. Objects tagged to the
session may also have the same lifetime as the session, which is
created per user and remains until the user logs out of the application.
Failure to clean up or free native system resources Native system resources are resources allocated by a function external to Java, typically native code written in C or C++.
Java Native Interface (JNI) APIs are used to embed native libraries/code into Java code.
Bugs in the JDK or third-party libraries Bugs in various versions of the JDK or in the Abstract Window Toolkit and Swing packages can cause memory leaks.