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.

If you enjoy this Java programming article, please share with friends and colleagues. Follow the author on Twitter for the latest news and rants.

Editorial page content written by Neil Coffey. Copyright © Javamex UK 2021. All rights reserved.