Friday, April 5, 2013

Threads signaling mechanisms in Java

In Java, there might be situations where you want to perform an operation on a certain thread and then, the same thread should wait for a certain condition before completing its task. This condition happens after another thread completes its execution.

For instance, we want to run a syncronous method on thread-1:


synchMethod(){
// do something...
callAsycnMethod(callback);
//we want to stop here and wait for the callback before returning
}
private class CallbackImpl implements Callback{
public void onComplete(){
//this thread should signal the waiting thread that finally the execution is completed
//and synchMethod() can return
}
}
view raw synch1.java hosted with ❤ by GitHub



A first option to do this is by using the wait() and notify() methods provided by Object class.
The first thread calls wait() and the callback thread calls notify().


synchMethod(){
// do something...
callAsycnMethod(callback);
synchronized(this){
try{
this.wait();
}catch(InterruptedException e){}
}
}
private class CallbackImpl implements Callback{
public void onComplete(){
synchronized(this){
this.notify();
}
}
}
view raw wait.java hosted with ❤ by GitHub
We must be carful though, because if the notify() method happens-before the wait() one, the waiting thread will wait forever.

To prevent this, we need a boolean variable, that can be used to prevent a similar scenario:



boolean signal = false;
synchMethod(){
// do something...
callAsycnMethod(callback);
synchronized(this){
while(!signal){
try{
this.wait();
}catch(InterruptedException e){}
}
}
//return after the callback finished
}
private class CallbackImpl implements Callback{
public void onComplete(){
synchronized(this){
this.signal = true;
this.notify();
}
}
}
view raw wait2.java hosted with ❤ by GitHub


It is also possible to use Semaphore class, from java.util.concurrent package and call acquire() and release() methods to do the same thing.

Take a look also at this interesting tutorial that deals with many important Java concurrency topics:
http://tutorials.jenkov.com/java-concurrency/index.html