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?