3

If variable of type int (integer) is inherently atomic in Java as per Effective Java's excerpt below, then why do we see inconsistent state of integer value in example: https://docs.oracle.com/javase/tutorial/essential/concurrency/syncmeth.html

The language specification guarantees that reading or writing a variable is atomic unless the variable is of type long or double [JLS, 17.4.7]. In other words, reading a variable other than a long or double is guaranteed to return a value that was stored into that variable by some thread, even if multiple threads modify the variable concurrently and without synchronization.

Above items are contradicting to me.

Arsaceus
  • 293
  • 2
  • 19
David Prun
  • 8,203
  • 16
  • 60
  • 86

2 Answers2

5

Your mistake is equating individual operations such as reading a value and writing a value to an operation such as incrementing, which requires multiple operations.

The example you link to contains examples of incrementing and decrementing an int variable. Those operations look like one operation in the code, but they are really two operations behind the scenes. To increment or decrement, you must read the value, change it, and then write the value.

Those operations must be synchronized to be the thread-safe because they consist of multiple operations that if interrupted would lead to incorrect values, due to race conditions.

Even if individual read or write operations are themselves consistent, a set of multiple operations needs to be synchronized to maintain consistency.

rgettman
  • 176,041
  • 30
  • 275
  • 357
  • I think I got a better insight after reading your answers: int is atomic, means operation to read bits of integer variable is atomic, right? so is writing bits back to integer variable. However, after I read bits, performing increment or decrements will cause inconsistent views because many threads may perform at different CPU time. Correct? – David Prun Feb 03 '16 at 19:04
  • 1
    Yes, each individual read or write is atomic, but incrementing and decrementing are not atomic. A thread may interrupt another thread that has just read its value, performing its change, but when the original thread finishes its operation, the interrupting thread's change is lost without external synchronization. – rgettman Feb 03 '16 at 19:07
1

Reading/writing an int is single atomic operation:

int a = 10; // writing
doSomething(a); // reading

On the other hand, increment and decrement statements consist of multiple operations:

a++;

is equivalent to:

a = a + 1; // reading and writing

a can be changed after reading the second a and before writing the total to the first a.

Eng.Fouad
  • 115,165
  • 71
  • 313
  • 417