Wednesday, October 21, 2009

Background



















Chapter 17 - The BooleanLock Utility

Java Thread Programming
Paul
Hyde






size=1>  size=2>Copyright � 1999 Sams
Publishing




















size=4>Background












size=2>Using the wait/notify mechanism effectively and correctly
requires discipline. It is easy to erroneously code in such a way
that a
size=2>wait() is
invoked just
size=2>after a
size=2>notify() has
been issued, resulting in the notification being completely missed.
This kind of mistake results in a very subtle race condition that
only shows up occasionally and can be painstakingly difficult to
track down. Wherever possible, the wait/notify mechanism should be
encapsulated within a class to insulate external classes from the
signaling complexity.












size=2>In this chapter, I present the face="Courier New" size=2>BooleanLock face=Arial size=2> class. It simply encapsulates a color=#010100 face="Courier New" size=2>boolean color=#010100 face=Arial size=2> variable and controls access to it
through
size=2>synchronized
methods. Multiple threads can safely interact with it. The
wait/notify mechanism is hidden within the class and missed
notifications are impossible. It also uses the
color=#010100 face=Arial size=2>Waiting for the Full
Timeout
technique
from
color=#008000 face=Arial size=2>Chapter 14, “Waiting for the Full
Timeout.”












face="Courier New" size=2>BooleanLock face=Arial size=2> can be used to conveniently signal between two
threads. The first thread can block waiting until the value is set
to
size=2>true. When the
second thread is ready, it can set the value to
color=#010100 face="Courier New" size=2>true color=#010100 face=Arial size=2> and the first thread will be
released from its blocked state.












face="Courier New" size=2>BooleanLock face=Arial size=2> can also be used to work around the problem of
long
size=2>synchronized
blocks. Normally, when a thread is blocked waiting to acquire
exclusive access to a lock (through
face="Courier New" size=2>synchronized face=Arial size=2>), it will size=2>not
respond to interrupts. In addition, there is no mechanism for
specifying a timeout value that indicates how long a thread should
wait to try to get into a
face="Courier New" size=2>synchronized face=Arial size=2> block. The face="Courier New" size=2>BooleanLock face=Arial size=2> utility can be used to provide an interruptible,
timeout-capable, technique for providing exclusive access to a block
of code.












valign="top" bgcolor="#FFFFFF">

Toc



No comments:

Post a Comment