1

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.

Augusto
  • 28,839
  • 5
  • 58
  • 88
  • Static blocks are being run on class loading, which means there are locks and all sort of skullduggery involved. Take a jstack and see if it sheds a light on how many threads there are and what their state is. – Kayaman Apr 01 '22 at 09:39

0 Answers0