0

If I delete "synchronized" , "Wait 3 seconds and exit" will not be printed.

But if I add "System.out.println(getStarted());" or "System.out.println(123);"... inside the while loop, "Wait 3 seconds and exit" will be printed.

I want to know why

public class Consistent {
    static boolean started = false;

    public synchronized static void setStarted() { //delete synchronized
        started = true;
    }

    public synchronized static boolean getStarted() {//delete synchronized 
        return started;
    }

    public static void main(String[] args) {
        Thread thread1 = new Thread(new Runnable() {
            public void run() {
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                }
                setStarted();
                System.out.println("started set to true");
            }
        });
        thread1.start();

        while (!getStarted()) {
            // wait until started
           // System.out.println(getStarted());


        }

        System.out.println("Wait 3 seconds and exit");
    }

}

1 Answers1

0

Without synchronized, there is no guarantee that the modifications made by one thread will be visible to the other threads that are synchronizing on the same object. This is because of the Java memory model that defines how the compiler and runtime can rearrange reads/writes to the variables, and how things can be optimized. The while loop may get the value of started once and keep that. With synchronized, modifications made to variables by one thread are visible to all other threads.

When you move println into the while loop, you introduce additional synchronization because println uses synchronized memory access internally.

This might help: http://tutorials.jenkov.com/java-concurrency/java-memory-model.html

Burak Serdar
  • 46,455
  • 3
  • 40
  • 59
  • 1
    `are visible to all other threads.` Small modification: the Java memory model only guarantees visibility for threads that `synchronized` on the same object. If a variable is written with synchronized but read without it, no such guarantee takes place. So it's not "all threads" but only threads that synchronize on the read properly. – markspace Oct 27 '21 at 03:17