javaatomic

What does "atomic" mean in programming?


In the Effective Java book, it states:

The language specification guarantees that reading or writing a variable is atomic unless the variable is of type long or double [JLS, 17.4.7].

What does "atomic" mean in the context of Java programming, or programming in general?


Solution

  • Here's an example: Suppose foo is a variable of type long, then the following operation is not an atomic operation (in Java):

    foo = 65465498L;
    

    Indeed, the variable is written using two separate operations: one that writes the first 32 bits, and a second one which writes the last 32 bits. That means that another thread might read the value of foo, and see the intermediate state.

    Making the operation atomic consists in using synchronization mechanisms in order to make sure that the operation is seen, from any other thread, as a single, atomic (i.e. not splittable in parts), operation. That means that any other thread, once the operation is made atomic, will either see the value of foo before the assignment, or after the assignment. But never the intermediate value.

    A simple way of doing this is to make the variable volatile:

    private volatile long foo;
    

    Or to synchronize every access to the variable:

    public synchronized void setFoo(long value) {
        this.foo = value;
    }
    
    public synchronized long getFoo() {
        return this.foo;
    }
    // no other use of foo outside of these two methods, unless also synchronized
    

    Or to replace it with an AtomicLong:

    private AtomicLong foo;