As I understood from "Java concurrency in practice" when one thread changes some shareable var value there is no guarantee that second thread sees that new value, unless it uses the same lock as first thread before reading. (page 37, figure 3.1). I made a little test and found that every time I change some var value in one thread, second always see it! Whithout any synchronization. What do I get wrong?
My code:
public class Application {
public int a = 5;
public int b = 3;
public static void main(String[] args) throws InterruptedException {
final Application app = new Application();
for (int i = 0; i < 20000; i++) {
Thread t = new Thread(new Runnable() {
@Override
public void run() {
app.a = 0;
app.b = 0;
}
});
t.start();
t.join();
if (app.a == 5 || app.b==3) System.out.println("Old value!");
app.a = 5;
app.b = 3;
}
}
}