Search code examples
javac++atomicvolatile

What is the difference between sequential consistency and atomicity?


I read that java volatile are sequential consistent but not atomic. For atomicity java provides different library.

Can someone explain difference between two, in simple english ?

(I believe the question scope includes C/C++ and hence adding those language tags to get bigger audience.)


Solution

  • Imagine those two variables in a class:

    int i = 0;
    volatile int v = 0;
    

    And those two methods

    void write() {
        i = 5;
        v = 2;
    }
    
    void read() {
        if (v == 2) { System.out.println(i); }
    }
    

    The volatile semantics guarantee that read will either print 5 or nothing (assuming no other methods are modifying the fields of course). If v were not volatile, read might as well print 0 because i = 5 and v = 2 could have been reordered. I guess that's what you mean by sequential consistency, which has a broader meaning.

    On the other hand, volatile does not guarantee atomicity. So if two threads call this method concurrently (v is the same volatile int):

    void increment() {
        v++;
    }
    

    you have no guarantee that v will be incremented by 2. This is because v++ is actually three statements:

    load v;
    increment v;
    store v;
    

    and because of thread interleaving v could only be incremented once (both thread will load the same value).