Summary

Chapter 17 - The BooleanLock Utility

Java Thread Programming
Paul Hyde
  Copyright 1999 Sams Publishing

Background
Using the wait/notify mechanism effectively and correctly requires discipline. It is easy to erroneously code in such a way that a wait() is invoked just after a 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.
In this chapter, I present the BooleanLock class. It simply encapsulates a boolean variable and controls access to it through 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 Waiting for the Full Timeout technique from Chapter 14, Waiting for the Full Timeout.
BooleanLock can be used to conveniently signal between two threads. The first thread can block waiting until the value is set to true . When the second thread is ready, it can set the value to true and the first thread will be released from its blocked state.
BooleanLock can also be used to work around the problem of long synchronized blocks. Normally, when a thread is blocked waiting to acquire exclusive access to a lock (through synchronized ), it will 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 synchronized block. The BooleanLock utility can be used to provide an interruptible, timeout-capable, technique for providing exclusive access to a block of code.

Toc


Java Thread Programming
Java Thread Programming
ISBN: 0672315858
EAN: 2147483647
Year: 2005
Pages: 149
Authors: Paul Hyde

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net