Lazy Dead End Initialization

When I launched the next program, it just hung forever, and it seems to me that this is due to a dead end .

From my understanding, I

  • The static field is isInitializedinitially set to false.
  • Then, the main thread creates a background thread whose start method sets isInitializedto true.
  • The main thread starts the background thread and waits for it to complete the call join.
  • Once the background thread is completed, there can be no doubt that it isInitializedshould be set to True.

But when I started the program, I found that it wasn’t printing anything; he just hangs!

public class Test {
    private static boolean isInitialized = false;

    static {
        Thread t = new Thread(new Runnable() {
            public void run() {
                isInitialized = true;
            }
        });
        t.start();
        try {
            t.join();
        } catch (InterruptedException e) {

        }
    }

    public static void main(String[] args) {
        System.out.println(isInitialized);
       }
    }

Can someone help me understand this behavior, is there some kind of dead end, if so, why?

+4

Source: https://habr.com/ru/post/1676631/


All Articles