0

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;
        }
    }
}
SergeiK
  • 345
  • 1
  • 4
  • 19
  • 1
    "There is _no guarantee_ that other threads _will_ see the value" is not the same statement as "there is _a guarantee_ that other threads _won't_ see the value". They may, or they may not, depending on your JVM implementation, your CPU, and the position of Venus with respect to Saturn. – Thomas Mar 11 '18 at 16:44
  • Something about the way you're conducting this test *smells*. I'm not convinced that you're testing what you think you are. – Makoto Mar 11 '18 at 16:45
  • 3
    1. You call join() which provides visibility guarantees. You need to try reading while the thread is running. Not after you've joined it. But anyway, your logic is flawed. It's basically similar to "I've been told that you can die if you cross the road without watching for cars first. Yet I've done that 10 times, and I'm still alive". – JB Nizet Mar 11 '18 at 16:45
  • You joined the writing thread before reading the variables, which AFAIK creates a memory barrier with visibility guarantees. – E_net4 Mar 11 '18 at 16:46

0 Answers0