Home > Blockchain >  Is declaring a field volatile enough in case of a single writing thread?
Is declaring a field volatile enough in case of a single writing thread?

Time:02-11

Consider the following code:

public class MyAtomicInteger {
    private volatile int value;

    public int get() {
        return value;
    }

    public void increment() {
        value  ;
    }

}

I was asked the following question during an interview: is this code thread-safe if only one thread calls increment() and multiple threads can call get()?

I understand that if we have multiple writing threads, race conditions can occur. However, when there is a single writing thread in each reading thread we will get the values in order, i.e. we won't read 0 after 1 because write of 1 happens before the first read of 1 and, consequently, all subsequent reads in the same thread. Is this reasoning correct, or I am missing something?

CodePudding user response:

It is sufficient to have only volatile.

What is required is that a happens-before edge needs to exist between the read and the write. Otherwise, there is a data race. And a volatile generates such happens before edges.

These happens-before edges prevent reading an older value after you read a newer value. A correctly synchronized program in Java is only allowed to have sequential consistent executions. Every sequential consistent execution is automatically coherent because coherence is a relaxation of sequential consistency. And coherence prevents reading an older value after a newer value is read.

[note] If you would have concurrent increments, with a volatile variable you will not have a data race, but you will have a race condition.

CodePudding user response:

Normally problems come from needing atomicity for the read-modify-write that is value ;. Since a single thread is doing it, it's just one thread writing value, other threads reading value.

That's what volatile provides (visibility from changes done by threads) and that's all what is required.

Of course everyone knows that it's still not safe to design code like that. Someone adds another thread and *bam* your code is broken without you noticing anything.

  • Related