Reputation: 9029
Have a small doubt on the correctness of "compare and swap " in java , because
i am still thinking this CAS also have a chance to lost the values , for example
lets a shared resource S , with the value 5
and threads T1 and T2 , want to update the values with the new values 6 and 7 respectively .
1 . T1 compare the value with 5 and found same 2. T2 compare the value with 5 and found same 3 . T2 set the values to 7 4. T1 set the value to 6
so now here the value set by the T2 lost as the T1 reads the old current value which is 5 at that time.
can anyone please explain on this please
Upvotes: 0
Views: 87
Reputation: 73528
What you described can't happen, due to the atomicity of CAS.
It's not "Compare-Then-Swap", it's "Compare-And-Swap". There's no separate phase for compare and another phase for swap. That's the whole beauty of it.
Upvotes: 2