Simple question: does the Java memory/synchronization model guarantee atomic pointer writes? That is, if we have competing threads:
String shared;
thread1()
{
shared = "a";
}
thread2()
{
shared = "hello world";
}
started at the same time, is shared
always guaranteed to be null
, "a"
, or "hello world"
?
The main risk is that only ptr is atomic. But this does not apply to the values pointed to. To be noted that especially pointers bring further synchronisation risk when you reassign the atomic pointer to a non atomic pointer.
Variables shared between multiple threads (e.g., instance variables of objects) have atomic assignment guaranteed by the Java language specification for all data types except for long s and double s.
An atomic reference is ideal to use when you need to share and change the state of an immutable object between multiple threads. That is a super dense statement, so I will break it down a bit. First, an immutable object is an object that is effectively not changed after construction.
Atomicity. Atomic operations are those operations that ALWAYS execute together. Either all of them execute together, or none of them executes. If an operation is atomic, then it cannot be partially complete, either it will be complete, or not start at all, but will not be incomplete.
Reads and writes are atomic for reference variables.
Source: http://docs.oracle.com/javase/tutorial/essential/concurrency/atomic.html
It is atomic.
However, in the example you gave, shared
's value isn't necessarly one of null
, a
or hello world
. It is possible that, without proper synchronization, each thread will never see the value set by other threads. So thread 1
will see a
and thread 2
will see hello world
at the same time.
Edit: Added references for the last paragraph for further reading
The JLS explains the order of operation performed by different threads, in Chapter 17 - Threads and Locks. Specifically, in the 17.4.5 Happens-before Order section. Also, the well-written Java Concurrency in Practice explains all of this thoroughly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With