javasynchronized

While the thread is working, the ordinary variables are flushed to main memory


As I understand it, the memory.a should be in worker cache memory when the thread is not stopped. example:

public class SynchronizedMemory {
    // non-visible
    private int a = 0;
    public SynchronizedMemory(int a) {
        this.a = a;
    }

    private static void test2() throws InterruptedException {
        SynchronizedMemory memory = new SynchronizedMemory(1);
        Object lock = new Object();
        new Thread(() -> {
            System.out.println("thread1 start................");
            while (memory.a != -1) {
                // When I comment out this line, the thread never jumps out of the loop
                synchronized (lock){}
            }
            System.out.println("thread1 stop................");
        },"thread1").start();
        // wait for thread1 to run
        Thread.sleep(1000);
        new Thread(() -> {
            memory.a = -1;
            // keep the thread alive, prevent it from being completed and refresh the changes back to main memory
            while (true){}
        },"thread2").start();
    }
}

As I understand it, the changed value for memory.a should be in worker cache memory when thread2 is not stopped. When I run the above code, thread1 exit the loop and finish. This means that the changed value for memory.a in thread2 has been flushed to main memory when thread2 is still running. So Can anyone explain this situation?


Solution

  • Java thread semantics guarantee that things will be visible under certain conditions. They give no guarantees about when things will not be visible!

    Since there is no synchronization between your threads, changes made by one of them may or may not be visible to the other.