Bat0u89
Bat0u89

Reputation: 438

Atomic statement ignored without volatile keyword

The java concurrency tutorial states that:

Reads and writes are atomic for reference variables and for most primitive variables (all types except long and double).
Reads and writes are atomic for all variables declared volatile (including long and double variables).

I created a simple experiment to test this

package experiment0;

public class Experiment0 {

    public static int i=9;

    public static void main(String[] args) {
        i=9;
        (new Thread(){
            public void run(){
                while(i==9){
                    //System.out.println("i==9");
                }
                System.out.println("\ni!=9");
            }
        }).start();
        (new Thread(){
            public void run(){
                try{
                    Thread.sleep(3000);
                    i=8;
                }catch(Exception e){

                }
            }
        }).start();
    }
}

When I run this code the program never gets terminated! In order for it to work I either have to uncomment the line inside the while loop of the first thread or declare i as volatile. Am I missing something? Is the documentation wrong and should it say that all primitives should be declared as volatiles in these kind of cases? Why does a write to System.out "solve" the problem? Does it give enough time to the second thread to change i?

Upvotes: 2

Views: 401

Answers (1)

JB Nizet
JB Nizet

Reputation: 691635

A write being atomic means that the write is executed as a single, atomic operation. No other thread could see something other than the value before the assignment, or after the assignment.

For example, in the case of long values, an assignment is not atomic because it's actualy executed as two operations: one which assigns the first 32 bits, and one which assigns the last 32 bits. So another thread might read the variable's value after only one of the two operations has been executed, ans thus see a value that is neither the before nor the after value, but an "in-between" value.

What your program demonstrates is that writing to a variable without any kind of synchronization causes visibility problems between threads. The write done by one thread is not visible by another thread. This is due to processors each having their own cache, and not writing to the main memory at each assignment. To make sure a write is visible, you need to make the variable volatile, or to synchronize access to the variable, or to use an AtomicInteger.

Upvotes: 3

Related Questions