O'Reilly logo

Java Cookbook by Ian F. Darwin

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Thread Communication: wait( ) and notifyAll( )

Problem

The synchronized keyword lets you lock out multiple threads, but doesn’t give you much communication between them.

Solution

Use wait( ) and notifyAll( ). Very carefully.

Discussion

Three methods appear in java.lang.Object that allow you to use any object as a synchronization target: wait( ), notify( ), and notifyAll( ).

wait( )

Causes the current thread to block in the given object until awakened by a notify( ) or notifyAll( ).

notify( )

Causes a randomly selected thread waiting on this object to be awakened. It must then try to regain the monitor lock. If the “wrong” thread is awakened, your program can deadlock.

notifyAll( )

Causes all threads waiting on the object to be awakened; each will then try to regain the monitor lock. Hopefully one will succeed.

The mechanism is a bit odd: there is no way to awaken only the thread that owns the lock. However, that’s how it works, and it’s the reason almost all programs use notifyAll( ) instead of notify( ). Also note that both wait( ) and the notification methods can be used only if you are already synchronized on the object; that is, you must be in a synchronized method within, or a code block synchronized on, the object that you wish your current thread to wait( ) or notify( ) upon.

For a simple introduction to wait( ) and notify( ), I’ll use a simple Producer-Consumer model. This pattern can be used to simulate a variety of real-world situations in which one object is creating ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required