Joshua Bloch "Effective Java", paragraph 51 is independent of the thread scheduler, and also does not require unnecessary threads in runnable state. Quoted text:
The main method of keeping the number of running threads down is to do a little work for each thread, and then wait for some state using Object.wait or for some time that needs to be done with Thread.sleep. Threads should not be busy - wait, repeatedly checking the data structure, expecting something. Besides the fact that the program is vulnerable to the vagaries of the scheduler, waiting for the wait can significantly increase the load on the processor, reducing the amount of useful work that other processes on the same machine can perform.
And then a microobject of lively expectation is shown against the proper use of signals. In the book, busy waiting makes 17 round trips / s, while the wait / notify version is 23,000 rounds per second.
However, when I tried the same JDK 1.6 benchmark, I see the exact opposite: the wait waits for 760K roundtrips / second, while the wait / notify version is 53.3K roundtrips / s, that is, wait / notify should have been ~ 1400 times faster but turned out to be ~ 13 times slower?
I understand that busy expectations are not very good, and the signaling is even better - CPU usage is ~ 50% in the expected version of the wait, while it remains ~ 30% in waiting / notification - but is there anything that explains the numbers?
If this helps, I run JDK1.6 (32 bit) on Win 7 x64 (i5 core).
UPDATE Source below. To start a busy desktop, change the base class PingPongQueue to BusyWorkQueue import java.util.LinkedList; import java.util.List;
abstract class SignalWorkQueue { private final List queue = new LinkedList(); private boolean stopped = false; protected SignalWorkQueue() { new WorkerThread().start(); } public final void enqueue(Object workItem) { synchronized (queue) { queue.add(workItem); queue.notify(); } } public final void stop() { synchronized (queue) { stopped = true; queue.notify(); } } protected abstract void processItem(Object workItem) throws InterruptedException; private class WorkerThread extends Thread { public void run() { while (true) {
java multithreading synchronization concurrency
Raghu
source share