Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 218
Brinal Avatar asked Dec 21 '22 13:12

Brinal


2 Answers

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.

like image 71
jjnguy Avatar answered Jan 10 '23 17:01

jjnguy


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.

like image 36
Joachim Sauer Avatar answered Jan 10 '23 15:01

Joachim Sauer