Doing a course on concurrent programming.
As an example we have
final class Counter {
private AtomicInteger value;
public long getValue() {
return value.get();
}
public long increment() {
int v;
do {
v = value.get();
}
while(!value.compareAndSet(v, v+1));
return v+1;
}
}
Why would you use compareAndSet in this case and not incrementAndGet ?
Thanks
Here the the implementation of
AtomicInteger.incrementAndGet()method from the JDK version I have on my machine:As you can see, the implementation is very similar to yours.
PS: Why do you compute
v+1twice?