achieve atomic operation because java volatile guarantees happens-before relation?
I have read about the happens-before for the volatile:
If Thread A writes to a volatile variable and Thread B subsequently reads the same volatilevariable, then all variables visible to Thread A before writing the volatile variable, will also be visible to Thread B after it has read the volatile variable.
Now, I have two varaibles:
static int m_x;
volatile static int m_y;
Now I have two threads, one only writes to them, and first write to m_x, and then write to m_y; The other one, only reads from them, first read m_y, and then, m_x.
My question is: is the write operation atomic? is the read operation atomic?
In my understanding, they should be atomic:
(1) On the side of writ thread, after (Write-1), it will not flush its cache to main-memory for m_x is NOT volatile, so, read-thread is not able to see the update; and after (Write-2), it will flush its cache to main-memory, for m_y is volatile;
(2) on the side of read thread, on (Read-1), it will update its cache from main memory, for m_y is volatile; and on (Read-2), it will NOT update its cache from main memory, for m_x is not volatile.
Because of the above two reason, I think the read thread should always observe the atomic value of the two variable. Right?
public class test {
static int m_x;
volatile static int m_y;
public static void main(String[] args) {
// write
new Thread() {
public
void run() {
while(true) {
int x = randInt(1, 1000000);
int y = -x;
m_x = x; // (Write-1)
m_y = y; // (Write-2)
}
}
}.start();
// read
new Thread() {
public
void run() {
while(true) {
int y = m_y; // (Read-1)
int x = m_x; // (Read-2)
int sum = y + x;
if (sum != 0) {
System.out.println("R:sum=" + sum);
System.out.println("R:x=" + x);
System.out.println("R:y=" + y);
System.out.println("\n");
}
}
}
}.start();
}
public static int randInt(int Min, int Max) {
return Min + (int)(Math.random() * ((Max - Min) + 1));
}
}