Threads should not busy-wait, repeatedly checking a shared object waiting for something to happen. Busy-waiting greatly increases the load on the processor, reducing the amount of useful work that others can accomplish. An extreme example of what not to do, consider this perverse implementation of CountDownLatch
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Awful CountDownLatch implementation - busy-waits incessantly! | |
public class SlowCountDownLatch { | |
private int count; | |
public SlowCountDownLatch(int count) { | |
if (count < 0) | |
throw new IllegalArgumentException(count + " < 0"); | |
this.count = count; | |
} | |
public void await() { | |
while (true) { | |
synchronized (this) { | |
if (count == 0) | |
return; | |
} | |
} | |
} | |
public synchronized void countDown() { | |
if (count != 0) | |
count--; | |
} | |
} |
No comments:
Post a Comment