It is possible to achieve what you suggest but it's not as easy as it sounds. A class can only be initialised in one thread and it can't accessed by another thread until this completes.
public class Main {
static class Deadlock {
static int NUM = 1;
static {
Thread t = new Thread(new Runnable() {
@Override
public void run() {
// tries to use NUM in a new thread
System.out.println(NUM);
}
});
t.start();
try {
t.join();
} catch (InterruptedException e) {
throw new AssertionError(e);
}
}
}
public static void main(String[] args) {
System.out.println("About to dead lock");
new Deadlock();
System.out.println(".. never gets here");
}
}
if you take a stack trace you see
"Thread-0" #11 prio=5 os_prio=0 tid=0x00007f9c2414a800 nid=0x2188 in Object.wait() [0x00007f9be983b000]
java.lang.Thread.State: RUNNABLE
at Main$Deadlock$1.run(Main.java:14)
at java.lang.Thread.run(Thread.java:745)
"main" #1 prio=5 os_prio=0 tid=0x00007f9c2400a000 nid=0x2163 in Object.wait() [0x00007f9c2caf0000]
java.lang.Thread.State: WAITING (on object monitor)
at java.lang.Object.wait(Native Method)
- waiting on <0x00000000fec64ec0> (a java.lang.Thread)
at java.lang.Thread.join(Thread.java:1245)
- locked <0x00000000fec64ec0> (a java.lang.Thread)
at java.lang.Thread.join(Thread.java:1319)
at Main$Deadlock.<clinit>(Main.java:19)
at Main.main(Main.java:28)
The main thread is waiting on the background thread to finish, however it can't get the value of NUM because the class hasn't finished initialising.