22 lines
442 B
Java
22 lines
442 B
Java
import java.util.concurrent.atomic.AtomicInteger;
|
|
import java.util.function.IntUnaryOperator;
|
|
|
|
class AtomicCounter {
|
|
private AtomicInteger i;
|
|
|
|
public AtomicCounter() {
|
|
this.i = new AtomicInteger(0);
|
|
};
|
|
|
|
public int updateAndGet(IntUnaryOperator op) {
|
|
// not safe if op is not a pure function
|
|
|
|
int oldVal;
|
|
|
|
do {
|
|
oldVal = i.get();
|
|
} while (!i.compareAndSet(oldVal, op.applyAsInt(oldVal)));
|
|
|
|
return op.applyAsInt(oldVal);
|
|
}
|
|
} |