concurrent

CountDownLatch example of a more general wait/notify mechanism

In this example we shall show you how to create a CountDownLatch of a more general wait/notify mechanism. We have implemented a method, that is testWaitNotify(). The steps of the method are described below:

  • It creates an Object, to be the mutex.
  • It creates a new Thread, that in its run() method acquires the object, using the synchronized() statement.
  • Although the object is held by the thread, calling its wait() method causes the current thread to wait until another thread invokes the java.lang.Object.notify() method or the java.lang.Object.notifyAll() method for this object.
  • Then the thread calls its start method to begin execution.
  • After a second the lock of the object is acquired in the method, that uses synchronized() statement. The thread now waits for the object to be released.
  • After calling notify() method of the Object, the thread waiting for the object waits up,

as described in the code snippet below.

public void testWaitNotify() throws Exception {
   final Object mutex = new Object();
   Thread t = new Thread() {

public void run() {

// we must acquire the lock before waiting to be notified

synchronized(mutex) {

   System.out.println("Going to wait " +

    "(lock held by " + Thread.currentThread().getName() + ")");

try {

   mutex.wait(); // this will release the lock to be notified (optional timeout can be supplied)

} catch (InterruptedException e) {

   e.printStackTrace();

} 

System.out.println("Done waiting " +

 "(lock held by " + Thread.currentThread().getName() + ")");

   }

}
   };

   t.start(); // start her up and let her wait()

   // not normally how we do things, but good enough for demonstration purposes
   Thread.sleep(1000);

   // we acquire the lock released by wait(), and notify()
   synchronized (mutex) {

System.out.println("Going to notify " +

 "(lock held by " + Thread.currentThread().getName() + ")");

mutex.notify();

System.out.println("Done notify " +

 "(lock held by " + Thread.currentThread().getName() + ")");
   }

}

Output:

Going to wait (lock held by Thread-0) Going to notify (lock held by main) Done notify (lock held by main) Done waiting (lock held by Thread-0)

 
This was an example of how to create a CountDownLatch of a more general wait/notify mechanism in Java.
 
Related Article:

Reference: Java Concurrency Part 6 – CountDownLatch from our JCG partners at the Carfey Software blog

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button