Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - is volatile required with synchronized?

In the following simple scenario:

class A {
  int x;
  Object lock;

  ...

  public void method(){
    synchronized(lock){
      // modify/read x and act upon its value
    }
  }
}

Does x need to be volatile? I know that synchronized guarantees atomicity, but I am not sure about visibility though... does lock -> modify -> unlock -> lock guarantee, that after the second lock the value of x will be "fresh"?

like image 401
Bober02 Avatar asked Apr 04 '14 12:04

Bober02


Video Answer


1 Answers

No it does not, because synchronized already has a memory barrier inserted after it, so all threads will see the update that the current thread performs, taking into account that the other threads will synchronize on the same lock.

Volatile, just like synchronized, has memory barriers that are attached to it - depending on the CPU, it is store/load/full barrier that ensures that an update from one thread is visible to the other(s). I assume this is performed with CPU cache invalidation.

EDIT From what I've just read, the store buffers are flushed to the CPU cache, and this is how the visibility is achieved.

like image 197
Eugene Avatar answered Oct 03 '22 06:10

Eugene