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

9 comments:

  1. It's totally amazing sharing I have no words in which I could explain how efficiently you did your job keep it up.

    Android Development

    ReplyDelete
  2. Does your blog have a contact page? I’m having problems locating it but, I’d like to shoot you an email. I’ve got some recommendations for your blog you might be interested in hearing.
    AWS Training in Chennai |Best Amazon Web Services Training in Chennai
    Best AWS Amazon Web Services Training in Chennai | AWS Training in Chennai cost
    No.1 AWS Training in Chennai | Amazon Web Services Training Institute in Chennai

    ReplyDelete
  3. This comment has been removed by the author.

    ReplyDelete
  4. Get our HTML5 responsive job portal website templates and easily customize your Job Portal template with our web design tools, site builder, and CMS today.

    ReplyDelete