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
When you run any Java program the Main thread is the first thread to start up.
The output you are seeing isn't indicating that the main
method is executing. Rather it is the main
thread.
So, anytime you fire up a Java program, you will have a thread called main executing. And, if that thread immediately exits the JVM, then that's all of the threads that will ever run.
To clarify:
As per my understanding static block is executed during the load time.
The static block is executed when the class is loaded. This happens by a class loader, and is executed in the main thread when a Java program starts up.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With