2

I'm reading "Effective Java Second Edition" by Joshua Bloch and im confused by below statement with regard to concurrency -

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

This is stated on last paragraph of page 259 in case anyone has book on hand.

Will the variable referred to not always have a value even if multiple threads are modifying it ?

blue-sky
  • 51,962
  • 152
  • 427
  • 752
  • 1
    4-4-byte atomic read/write. it essentially means a variable that is comprised of 2 x 4byte locations is not guaranteed to be in a completely written or read state. – Mitch Wheat Nov 30 '11 at 23:59

3 Answers3

4

You have to read the sentence as a whole. Here, let me reword it for you:

"In other words, reading a variable other than a long or double is gauranteed to return a value that was stored into that variable by some thread, even if multiple threads modify the variable concurrently and without synchronization"

becomes:

"Let's assume the variable isn't a long or a double (because then special rules apply). Even if there are multiple threads modifying the variable at the same time without synchronization to protect it, then a variable will always have a value.

This value will always be one of the values that one of the threads wrote. You won't be able to tell which one ahead of time, but it will always be a value that one of them wrote. It won't ever be a corrupt half-and-half value."

kittylyst
  • 5,640
  • 2
  • 23
  • 36
1

If you have multiple threads writing and reading to/from a double or long not appended with the volatile keyword. It is possible for the read to get a value that was never written before.

The reason for this is that these are 8 bytes long rather than 4 bytes long, so you may read half of variable's new value and the other half of old value (may not be quite this simple based on particular architecture, but this is the idea), result in a incorrect read that was NEVER written to it.

Desmond Zhou
  • 1,369
  • 1
  • 11
  • 18
0

He is saying the variable will have a value, but that value is non-deterministic (due to the actions of your concurrent threads on the variable).

sarumont
  • 1,734
  • 12
  • 11