Asdfasf

Friday, September 26, 2014

EJ-72 Threads should not run if they aren't doing useful work

Ref: Effective Java by Joshua Bloch

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

// 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--;
}
}
view raw WhileTrue.java hosted with ❤ by GitHub

No comments: