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:





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().


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:





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

2 comments: