As far as I know, for space in old generation of JVM, it could be utilized for two purposes,
- used for objects promoted from young generation to old generation?
- used for new object allocation in special use cases (https://stackoverflow.com/questions/9053144/will-i-encounter-java-lang-outofmemoryerror-even-with-no-lack-of-memory)
My questions are,
- Are there any other use cases to which will utilize space in old generation?
- I think there is a memory copy involved to copy objects from young generation to old generation, is it a deep copy or a shallow copy?
thanks in advance,
Lin
Let me answer 2. It is definitely not a deep copy: the GC handles objects as distinct memory blocks and deep copying really only means copying many distinct objects that are connected into an object graph. Also, you'd be better served by imagining a move, not a copy; copying is in fact just an "implementation detail" and the desired effect is relocating.
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.