Additional Notes on wait and notify


The Object class overloads the wait method with versions that allow you to specify a timeout period. A thread you suspend using one of these versions of wait idles until another thread notifies it or until the timeout period has expired.

Under certain circumstances, it is possible for a spurious wakeup to occurone that you did not trigger by an explicit notification! This is rare, but if you use wait and notify in production code, you need to guard against this condition. To do so, you can enclose the wait statement in a while loop that tests a condition indicating whether or not execution can proceed. The Java API documentation for the wait method shows how you might implement this.

In a test, you could create a do-while loop that called the verify method each time through. If the verify method were to then fail, you would execute wait again. I view this as an unnecessary complexity for a test. The worst case of not guarding against the unlikely spurious wakeup would be that the test would fail, at which time you could rerun it.

While notifyAll wakes up all threads that are waiting if there is more than one, the notify method chooses an arbitrary thread to be woken up. In most circumstances you will want to use notifyAll. However, in some situations you will want to wake up only a single thread. An example is a thread pool.

The search server currently uses a single thread to process incoming requests. Clients eventually get the results of their search in an asynchronous fashion. While this may be fine for a small number of requests, clients could end up waiting quite a while if a number of other clients have requested searches ahead of them.

You might consider spawning each search request off in a new, separate thread as it arrives. However, each Java thread you create and start carries with it significant overhead costs. Creating one thread for each of thousands of search requests would result in severe performance problems. The Java thread scheduler would spend more time context-switching between threads than it would processing each thread.

A thread pool collects an arbitrary, smaller number of worker Thread objects that it creates and starts running. As a search comes in, you pass it off to the pool. The pool adds the work to the end of a queue, then issues a notify message. Any worker thread that has completed its work checks the queue for any pending tasks. If no tasks are available, the worker thread sits in an idle state by blocking on a wait call. If there are idle threads, the notify message will wake up one of them. The awakened worker thread can then grab and process the next available piece of work.



Agile Java. Crafting Code with Test-Driven Development
Agile Javaв„ў: Crafting Code with Test-Driven Development
ISBN: 0131482394
EAN: 2147483647
Year: 2003
Pages: 391
Authors: Jeff Langr

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