Is a volatile int in Java thread-safe?

后端 未结 6 1638
北荒
北荒 2020-11-27 02:47

Is a volatile int in Java thread-safe? That is, can it be safely read from and written to without locking?

6条回答
  •  时光取名叫无心
    2020-11-27 03:27

    1) If two threads are both reading and writing to a shared variable, then using the volatile keyword for that is not enough. You need to use a synchronized in that case to guarantee that the reading and writing of the variable is atomic. Reading or writing a volatile variable does not block threads reading or writing. For this to happen you must use the synchronized keyword around critical sections.

    2) As an alternative to a synchronized block you could also use one of the many atomic data types found in the java.util.concurrent package. For instance, the AtomicLong or AtomicReference or one of the others.

    It's thread safe if you have one writer thread and multiple reader threads.

    class Foo {
    private volatile Helper helper = null;
    public Helper getHelper() {
    if (helper == null) {
    synchronized(this) {
    if (helper == null)
    helper = new Helper();
    }
    }
    return helper;
    }
    }
    

    Note : If helper is immutable then no need of volatile keyword.Here singleton will work properly.

    In case of counter which is being incremented by multiple threads (reading writing operation) will not give correct answer. This condition is also illustrated by race condition.

    public class Counter{
    private volatile int i;
    public int increment(){
    i++;
    }
    }
    

    NOTE : Here volatile will not help.

提交回复
热议问题