Reputation: 3390
Suppose I have -
public class ThreadingIssue {
public B b = new B();
}
class B{
private final Object lock = new Object();
public void someMethod(int timeOut){
synchronized(lock){
try{
lock.wait(timeOut);
}catch(Exception e){
}
// some task..
lock.notifyAll();
}
}
}
class Thread1 implements Runnable{
private ThreadingIssue t;
public Thread1(ThreadingIssue issue) {
t = issue;
}
public void run(){
while(true){
t.b.someMethod(5000);
}
}
}
class Thread2 implements Runnable{
private ThreadingIssue t;
public Thread2(ThreadingIssue issue){
t = issue;
}
public void run(){
try{
Thread.sleep(2000);
}catch(Exception e){
}
t.b = null;
}
}
what can happen to Thread1, if it is inside someMethod(5000)
of B and waiting for lock, and Thread2 has made B's object to null? I am unsure whether Thread1 will throw which exception.. any help?
Upvotes: 1
Views: 540
Reputation: 1872
Summarising SJuan76 and the op's discussion:
Looks like there are two references to t, but only one to b (the one inside t).
t will not get released, because the threads hold it independently. However, b may be deleted (depending on gc) because its ref count will drop to zero once the reference is nullified.
So Thread2 may throw a NullPointerException.
Edit:
Inside someMethod(), the b object will not be freed, because the this
pointer is held on the stack, making the ref count 1, at least. You can say the same thing for every execution of a member method since every one of them get this
as an argument.
Please note that although you get a NullPointerException, it doesn't mean the object is finalized/freed already, just that the reference you are using is null. The GC may take some time to actually free the object.
Upvotes: 1
Reputation: 24885
The second thread holds a reference to the object whose method it is running (otherwise it would not be able to run its instance methods), so the GC cannot dispose of the object so there is no possibility of Exception.
To be more explicit with your code, when you do
t.b.someMethod(5000)
internally the JVM process the t.b
expression (which is a reference to the object), so the reference count is not 0.
Upvotes: 3