What is the difference between sequential consiste

2019-04-26 19:47发布

问题:

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.)

回答1:

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).



回答2:

Suppose you have these two variables:

public int a = 0;
public volatile int b = 0;

And suppose one thread does

a = 1;
b = 2;

If another thread reads these values and sees that b == 2, then it's guaranteed to also see a == 1.

But the reading thread could see a == 1 and b == 0, because the two writes are not part of an atomic operation, so the reading thread might see the change made to a before the first thread has assigned a value to b.

To make these two writes atomic, you would need to synchronize the access to these two variables:

synchronized (lock) {
    a = 1;
    b = 2;
}

...

synchronized (lock) {
    System.out.println("a = " + a + "; b = " + b);
}

And in this case, the reading thread will see a == 0 and b == 0, or a == 1 and b == 2, but never the intermediate state.