IBM (see Source) wrote on the benefits of Java’s 1.5 java.util.concurrent class, which offers non-blocking queues.
Please explain the weaknesses/disadvantages of the NonBlockingCounter below.
public class NonblockingCounter {
private AtomicInteger value;
public int getValue() {
return value.get();
}
public int increment() {
int v;
do {
v = value.get();
}
while (!value.compareAndSet(v, v + 1)); // params - (actual, expected)
return v + 1;
}
}
Source – http://www.ibm.com/developerworks/java/library/j-jtp04186/index.html
The disadvantage is that it spins while trying to increment the value if there’s contention. That means it’s bad for high-contention locks.
The advantage is that it doesn’t have lock acquistion/semaphore overhead. That’s good for low-contention locks.