3

This class does not initialize itself in the usual way, so it calls on the help of background thread.

From my understanding ,surely the program must print true ?

But If you ran the program, you found that it prints nothing; it 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 some one please explain why this is happening.

T-Bag
  • 10,916
  • 3
  • 54
  • 118

1 Answers1

4

"The static initializer for a class gets run when the class is first accessed, either to create an instance, or to access a static method or field." Static Initialization Blocks

I guess that this program to start needs to first initialize the class Test. And so it tries first to execute static block but that block never exits (since it cannot set static member isInitialized as it is not ready yet). So Test class is never fully initialized and therefore main method is not even starting to be executed.

The solution for you could be moving the instruction of waiting for your initialization thread to finish - to the main method. So it does not block the Test class from being fully initailzed.

package com.company;

public class Test {
    private static boolean isInitialized = false;

    static Thread t = new Thread(new Runnable() {
        public void run() {
            isInitialized = true;
        }
    });
    static {
        t.start();
    }

    public static void main(String[] args) {
        try {
            t.join();
        } catch (InterruptedException ignored) { }

        System.out.println(isInitialized);
    }
}
Community
  • 1
  • 1
alwi
  • 431
  • 6
  • 21