Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are Java pointer writes atomic?

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"?

like image 516
donnyton Avatar asked Jun 20 '12 22:06

donnyton


People also ask

Are pointers Atomic?

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.

Is Java variable assignment Atomic?

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.

When to use AtomicReference?

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.

What are atomic operations Java?

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.


2 Answers

Reads and writes are atomic for reference variables.

Source: http://docs.oracle.com/javase/tutorial/essential/concurrency/atomic.html

like image 109
Stefan Haustein Avatar answered Oct 06 '22 00:10

Stefan Haustein


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.

like image 43
yair Avatar answered Oct 05 '22 22:10

yair