Search code examples
javamultithreadingmain-method

Does the Java main method start an infinite while-loop?


This question might be a really newbie one, but it's pretty confusing to me. I'm working on Java networking, and I'm curious as to the back-end of the main method.

public static void main(String[] args) throws IOException 

I understand it that the main starts one thread? So even if I have a simple "Helloworld" program, a thread stays alive until you close the whole IDE or system?

Does that mean I can include any arbitrary code in the main method, which I want to run forever too( for example, a heartbeat sensor check or some other checks).

thanks


Solution

  • No. The JVM starts a thread (the main thread) and executes your main method inside this thread. As soon as the main method returns, if there is no other non-daemon thread running, the JVM exits.

    You can run an infinite loop in the main method, and the JVM will never exit (unless it's killed from the outside).