javamultithreadingconcurrency

What is out-of-thin-air safety?


I'd like to understand this line from Java Concurrency in Practice -

Out-of-thin-air safety is the safety guarantee that when a thread reads a variable without synchronization it may see a stale value, but the value will be one set by a thread, not some random value.

What's meant by the value being random? How could it get into that state? An example in pseudocode would be very helpful.


Solution

  • The best example I can think of is writing a long in a 32 bit CPU.

    According to the Java standard, long has to be 64 bit wide. A 32 bit CPU cannot write a long value in one atomic write, it has to write two 32 bit integers in order to achieve that.

    Assuming A thread wrote only the first 32 bit value, then, the OS scheduled another (Java) thread on the same core that tries to read that semi-updated value - it will see random value. the quote you gave basically says "that cannot happen".