Reputation: 2948
Example: Lets say ideally that object is garbage collectable (activity changed orientation and strong reference to object lost) but not yet disposed. So line 2 will return true. Is there any way that object get disposed while execution is on line 3? Or it wait until it finishes?
new Thread {
WeakReference item= new WeakReference(object);
void method(){
2 if(item.get()!=null)
3 item.get().getName();
}
}
Upvotes: 3
Views: 1316
Reputation: 28516
If you have strong reference to an object then that object is not eligible for GC.
There is no way strong referenced object will get disposed in code between null check and next line... or any other line as long as you can access that object
reference. Only if you set that object reference to null, or you assign another object to that reference, previous object can be garbage collected if there are no other references pointing to it.
On the other hand, when you are dealing with weak references (of any kind) first you have to take strong reference out of weak reference wrapper and then you can safely use that strong reference further on (after you check it is not null, of course). If you don't take strong reference, object in weak wrapper can vanish at any time.
Wrong usage - object can be collected between null check and getName
call
if(item.get()!=null)
item.get().getName();
Correct usage - taking strong reference for further processing
Object object = item.get();
if(object!=null)
object.getName();
Upvotes: 6
Reputation: 1730
First of all Garbage Collector does not run on what you think as your proccess's main thread. When looking from Operating System's prospective, GC may run either in main thread of the virtual machine that runs your application. Or it can run on a new thread.
But from Java prospective, GC does not run on any of your application's thread. The thread that run GC is neither your Java main thread nor a Java thread accessible to you.
From the prospective of your Java code, the main thread and all other thread are stopped (removed from scheduler) while GC runs. This is not always true though. But that is up to the VM implementation. But you must always assume that all your Java threads, including main thread are stopped while GC runs.
So, to precisely answer your question, **
Yes, your week reference can become null in the second line.
**
Your code can get a NullPointerException in line three.
Because line 2 and 3 are two seperate non antomic operations. It is possible that GC can cick in after executing line 2 , stop execution of all your threads, do garbage collection , and then resume all your threads causing a NullPointerException to occur at line 3.
Upvotes: 4