Placing this code in response to the question by @Lin Ma in his comment:
class SomeClass{
private static List<Object> memoryLeakCulprit = new ArrayList<Object>();
void someMethod(Object obj){
//adding the reference of some object in the culprit list
memoryLeakCulprit.add(obj);
}
//supposed to remove the reference passed
void someOtherMethod(Object obj){
obj = null;
//bummer forgot to remove the reference from list
//now the instance is not reachable by obj
//so now as new references are added to culprit list the memory will keep on increasing in size
}
}
UDPATE
How to solve this leak
oid someOtherMethod(Object obj){
//before setting the obj reference to null it must be removed from culprit list
memoryLeakCulprit.remove(obj);
//now its safe to set this reference to null
obj = null;
}
Only way to solve the leak it to Profile the application using some profiling tools such as JProfiler, VisualVM and find out which class is causing the leak.
When you find the class, THE CODE WILL HAVE TO BE CHANGED and that is the only way.
There is no need to free the references before the program exiting. Reason is that static
variables (memoryLeakCulprit
) are bound to Class object, and as soon as you exit the program all the references are automatically freed including the Class Object.
On totally other note always make sure to close System Resources (Sockets, DB connections) before exiting the program.