Issue
Studying the atomic classes i found this code :
public class AtomicCounter {
private AtomicLong count = new AtomicLong(0);
public void increment() {
boolean updated = false;
while(!updated){
long prevCount = count.get();
updated = count.compareAndSet(prevCount, prevCount + 1);
}
}
public long count() {
return count.get();
}
And i asked myself what if the following scenario occurs :
In thread A the boolean updated is changed to true after calling the method
compareAndSet
.In thread B the instruction
boolean updated = false;
is executed and the boolean updated is changed again to be falseIn thread A the loop while check the value of the boolean updated which recently changed to false so another leap will be take a place.
In this case the thread A will take a new leap in while even it has already change the value of updated to true because in the time between of this change and the checking of updated by while the other thread B has changed the value of updated to false. How far this scenario is true ?
Solution
Local variable not shared between threads
You misunderstand how local variables work with threads.
👉 Each thread has its own local variables.
Local variables are kept on the call stack. Each thread has its own call stack. So in your scenario, two updated
vars exist.
See the Question, Why are local variables thread safe in Java.
So your threads A and B each have their own updated
variable. One thread changing the value updated
has no effect on the other thread’s updated
variable.
How far this scenario is true ?
Step # 1 is correct.
Steps 2 & 3 are incorrect.
Answered By - Basil Bourque
Answer Checked By - Robin (JavaFixing Admin)