Ok. I wrote the code and get unexpected result of it and I don't know how to explain this result. Can someone help me with this?
public class JMM {
static volatile Boolean ready = false;
static volatile int data = 0;
public static void main() {
Log.d("JMM", "start");
new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
data = 1;
ready = true;
}
}).start();
for(int i = 0; i < 100; i++) {
new Thread(new Runnable() {
@Override
public void run() {
while (!ready)
Log.d("JMM", "second thread data " + data);
}
}).start();
}
}
}
I executed it on Nexus 5 (it has 4 cores):
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
MM.main();
}
result:
D/JMM: second thread data 0
...
D/JMM: second thread data 0
D/JMM: second thread data 0
D/JMM: second thread data 0
D/JMM: second thread data 0
D/JMM: second thread data 0
D/JMM: second thread data 1
D/JMM: second thread data 1
D/JMM: second thread data 1
D/JMM: second thread data 0
D/JMM: second thread data 0
D/JMM: second thread data 1
D/JMM: second thread data 1
D/JMM: second thread data 1
D/JMM: second thread data 1
What I expect? That int is atomic type by default (however I wrote volatile before) and it doesn't cached it's value. But I see that different threads read different values from one field in same moment. Who can explain this to me?