Home > OS >  What is Atomicity in Java
What is Atomicity in Java

Time:03-22

I am studying JAVA concurrency in Practice and found the following definition of Atomic Operation:

Operation A, B are atomic with respect to each other if from the perspective of thread executing A, when another thread executes B, either all of B has executed or none of it has. An atomic operation is one that is atomic with respect to all operation, including itself, that operates on the same data.

Lets say I have two thread A & B both accessing AtomicLong variable count.
Lets say thread A reads count and thread B was busy doing count.incrementAndGe() operation.
In such a scenario, As per above definition (either all of B has executed or none of it ):

A) ThreadA see the previous value of count (because count is not yet updated)

Or

B) ThreadA will wait until ThreadB completes the operation and see the latest value.

As per my understanding it should B because otherwise we still could have race condition.

CodePudding user response:

The situation you have described is called a "data race." Either thread A will win the race (it sees the initial value), or thread B will win the race (thread A sees the final value.) Unless you have provided some explicit means to force the threads to access the variable in a particular order, then there is no way to know who will win the race.


"Atomicity" means that thread B will either see the data as it was before the atomic operation, or it will see it after the operation is complete. Thread B can never see it in a half-way-done state.

For an update to a single, 64-bit long value. Pretty much the only way it could be "half-way-done" is if the 64-bit value were torn on 32-bit hardware. It would be "torn" if one of the two 32-bit words comprising the 64-bit value had been updated, and the other had not.

  • Related