Site Search:

CasCounter.java

 CasCounter.java

/**
* CasCounter
* <p/>
* Nonblocking counter using CAS
*/
public class CasCounter {
private SimulatedCAS value;

public CasCounter() {
this.value = new SimulatedCAS();
}

public int getValue() {
return value.get();
}

public int increment() {
int v;
do {
v = value.get();
} while (v != value.compareAndSwap(v, v + 1));
return v + 1;
}

public static void main(String...args) {
CasCounter cc = new CasCounter();
int target = 9705;
for(int i = 0; i < target; i++) {
new Thread(() -> cc.increment()).start();
}
System.out.println(cc.getValue());
}
}

The CasCounter class is a simple nonblocking counter implementation that uses a simulated Compare-And-Swap (CAS) loop to achieve thread-safe increments without traditional locking. Internally, it relies on the SimulatedCAS class to atomically compare and update the current value. The increment() method uses a retry loop: it repeatedly reads the current value and attempts to update it to the next integer, retrying until the CAS succeeds. This pattern reflects how true nonblocking atomic counters like AtomicInteger work in Java, using hardware-supported CAS to avoid the overhead of synchronization. The main method launches thousands of threads to concurrently increment the counter, demonstrating how CAS can be used to maintain correctness even under heavy contention.

No comments:

Post a Comment