javajvmstatic-block

Static Block and Main Thread


I found a very interesting thing while trying with java. Please find the code below:

public class SimpleTest { 
    static{ 
        System.out.println(Thread.currentThread().getName()); 
        System.exit(0); 
    } 
} 

The above program runs without any exception (Well & good since I'm exiting in the static block itself). But i got the following as the output:

main

Since I haven't started the main thread, how does it got created. As per my understanding static block is executed during the load time. Then how does main thread come into picture?

Can anyone please give the brief introduction how the compilation, loading and execution done in jvm? Also the use of rt.jar?

Thanks in advance, Brinal


Solution

  • The main class is loaded and initialized on the main thread. Although this is not documented explicitly anywhere (as far as I know), it's a pretty safe assumption, as there's hardly a reason to implement it differently.