Home  Synchronization and concurrency  wait/notify  final  volatile  synchronized keyword  Java threading  Deadlock (and avoiding it)  Java 5: ConcurrentHashMap  Atomic variables  Explicit locks  Queues  Semaphores  CountDownLatch  CyclicBarrier

When to use wait()/notify() in Java?

If you are using a version prior to Java 5, then the wait/notify mechanism can be a key part of thread programming. It is generally used in situations where you need to communicate between two threads. This includes cases such as the following:

  • For controlling shared resources ("pooling") such as database connections. If all resources are currently in use, one thread can wait to be notified that a resource has become available.
  • For background execution or coordinating multi-threaded execution: the controlling thread can wait for other threads to notify it of completion of a task.
  • For creating thread pools or job queues on a server: a fixed number of threads would sit waiting to be notified that a new job had been added to the list.

Wait()/notify() in Java 5

As of Java 5, there is less need for programmers to use wait()/notify(), since other classes are available in the Java concurrency package (java.util.concurrent) to handle these common situations. For example:

  • In a common producer-consumer pattern, such as a logging thread, it is generally preferable to use a blocking queue;
  • To coordinate threads, for example to parallelise a task, it is generally more convenient to use a countdown latch.

Next: how to use wait/notify

On the next page, we'll continue by looking at how to use wait/notify in Java.

Article written by Neil Coffey (@BitterCoffey).

Software

 LetterMeister (word puzzle game for iPhone)
 Currency Quoter (currency converter/predictor)
 French Vocab Games for iPhone/iPad
 Vocabularium: create Spanish vocab podcasts


Java programming articles and tutorials on this site are written by Neil Coffey (@BitterCoffey). Suggestions are always welcome if you wish to suggest topics for Java tutorials or programming articles, or if you simply have a programming question that you would like to see answered on this site. Most topics will be considered. But in particular, the site aims to provide tutorials and information on topics that aren't well covered elsewhere, or on Java performance information that is poorly described or understood. Suggestions may be made via the Javamex blog (see the site's front page for details).
Copyright © Neil Coffey 2015. All rights reserved.