0

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

user207421
  • 305,947
  • 44
  • 307
  • 483
Caffeinated
  • 11,982
  • 40
  • 122
  • 216
  • 3
    The JVM doesn't stay alive unless a non-daemon thread is continuing to run, and this won't occur unless the coder explicitly or implicitly (such as running a Swing GUI) creates one or somehow keeps the main non-daemon thread alive (such as with a while loop). – Hovercraft Full Of Eels Mar 09 '13 at 21:03
  • 1
    But remember again that some libraries if started can create and have a non-daemon thread running, such as the Swing library as I've noted above. I'm sure that there are other examples of this. – Hovercraft Full Of Eels Mar 09 '13 at 21:06
  • @HovercraftFullOfEels - OK cool - so starting a Swing GUI creates a non-daemon thread. I'll study-up on this! thank you! – Caffeinated Mar 09 '13 at 21:12
  • 2
    The non-daemon thread only starts if you make the GUI visible, and care must be taken to make these calls on the Swing event thread only (via `SwingUtilities.invokeLater(...)`). If your primary purpose is not to create a Swing GUI, then I wouldn't use this at all. – Hovercraft Full Of Eels Mar 09 '13 at 21:17

1 Answers1

11

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).

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255