Starting a thread in static block doesn't run until it exits the static block

Viewed 52

I'm working on a app that has a few issues, and noticed that some threads are started in static blocks. I know this is a horrendous, vile practice which will be addressed, but the interesting thing I found is that the threads don't actually start until the static block exits.

Here is an simple example that blocks indefinitely

public class Main {
    public static void main(String[] args) {
        new Static().sayHello();
    }
}
public class Static {
    static {
        var thread = new Thread(()-> System.out.println("I'm running"));

        thread.start();

        try {
            thread.join(); // Hangs in here
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    public void sayHello() {
        System.out.println("Hello");
    }
}

The text I'm running is never printed and this hangs forever.

Any idea why this happens? I thought the thread should start nortmally, but it looks like being inside a static block makes a difference. I'm running this on openjdk 11.0.13.

0 Answers
Related