For instance, we want to run a syncronous method on thread-1:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
} |
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().
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} | |
} | |
} |
To prevent this, we need a boolean variable, that can be used to prevent a similar scenario:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} | |
} | |
} |
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