It's been quite long time I am involved in java development but I have never heard about invisible objects. We mainly know about unreachable objects while going through garbage collection mechanism in java.
Invisible objects are quite different than unreachable objects in following respects:
1. unreachable objects are those objects which doesn't has any references to them but in case of invisible object they have strong references assoicated with them but thses refrences are not available to any thread stack, making object invisible to garbage collector.
2. unreachable objects are eligible for GC and normally don't cause memory leak, while invisible objects are not eligible for gorbage collection causing memory leak
3. invisible objects are result of efficient implemenation of JVM which don't nullify references if they are out of scope unless the method is thrown from thread stack upon execution.
Lets take one exampe to explain it more clearly
public void run(){
try{
MyOject o = new MyObect();//1
o.callMyMethod();
} catch (Exception e){}
//do lot of other time taking things
}
at line 1 we have created an object, ideally when thread will complete try block, reference "o" will go out of scope and should be removed from stack making MyObject unreachable so eligible for garbage collection. But an efficient jvm implementation will not do that, it will retain the reference "o" referring to MyObject unless run method is executed and thrown out of thread stack. Since reference "o" is not available to thread's stack so it's invisible to garbage collector.
The best way to avoid this situation is set the reference "o" explicitly null in try block once we are done with it.
No comments:
Post a Comment