I am studying multithreading in java.
I have a class
public class CASCount<T> {
private final AtomicReference<Integer> count = new AtomicReference<>(0);
public int get() {
return count.get();
}
}
and there is a increment method :
public void increment() {
int t;
do {
t = count.get();
}
while (!count.compareAndSet(t, t + 1));
}
which could be simplified like this:
public void increment() {
int t;
while (!count.compareAndSet(t = count.get(), t + 1));
}
or like this:
public void increment() {
while (!count.compareAndSet(count.get(), count.get() +1));
}
I have been told that I couldn't because other threads could change the data inside the method. But, as I know, Compare and Set(CAS) is an atomic operation, and if the first get() returns 0 and the second get() returns 1, the CAS operation cannot change the counter, because if get() returns 1, it means the data has already changed.
My question is why I can not do the above operations if CAS is atomic, and why it is not advisable to do so?