36

I was teaching myself Java threading and I noticed something that confuses me a little. I made a class called engine implementing Runnable. The run method just prints "Hello World", sleeps for a second, and repeats.

In my main method, I have:

public static void main(String[] args) {
    Thread thread = new Thread(engine);
    thread.start();
    System.out.println("Done.");
}

As I expected, I see "Hello World" and "Done." printed quickly, meaning the main method has reached the end, but what I didn't expect was that the thread I started kept running even after the end of main was reached.

Why does the program continue to execute even after main exits? I would have thought that when main exited the process would terminate and all of the threads would be cleaned up forcefully. Does this mean that every thread has to be joined/killed explicitly for a Java program to terminate?

3
  • My guess is that the program is finished when all threads are finished. If your thread is on a loop, then the program won't finish until it terminates.
    – gsgx
    Dec 16, 2012 at 19:29
  • Just to make sure I'm not going nuts (I always code joins without thinking in C), if I did this in a C program then it would forcefully terminate the thread, right? Dec 16, 2012 at 19:39
  • From Concurrency in Practice "If any application threads (daemon or nondaemon) are still running at shutdown time, they continue to run concurrently with the shutdown process. ... The JVM makes no attempt to stop or interrupt any application threads that are still running at shutdown time; they are abruptly terminated when the JVM eventually halts". Thus, your thread has more stuff to do (like gsingh2011 said above)
    – ampofila
    Feb 20, 2020 at 14:13

6 Answers 6

32

Because that's how it works. The program exits when System.exit() is called, or when the last non-daemon thread stops running.

And it makes sense. Without this rule, every Java program consisting in just spawning a GUI, for example, would have to wait() infinitely to avoid the program from exiting immediately.

1
  • Thanks for the answer, helpful way of looking at it :) +1 Dec 16, 2012 at 19:44
29

If you want your program to exit when the main method finished, consider making your threads daemons. But take care of the fact, that daemon threads will be aborted, when main finishes.
You can create a daemon thead like so:

Thread t = new Thread(...);
t.setDaemon(true);

All non-daemon threads are user threads. Those threads are stopping the jvm from closing.

2
  • 5
    "daemon threads will be aborted, when main exits". That's true only if all created threads are daemons. The rule is that the JVM exits once the only running threads are daemon threads, but daemons can certainly outlive main.
    – Boann
    Aug 19, 2014 at 10:26
  • From Concurrency in Practice: "When a thread exits, the JVM performs an inventory of running threads, and if the only threads that are left are daemon threads, it initiates an orderly shutdown. When the JVM halts, any remaining daemon threads are abandoned. Finally blocks are not executed, stacks are not unwound - the JVM just exists. ... it is dangerous to to use daemon threads for tasks that might perform any sort of I/O ... best saved for 'housekeeping' tasks"
    – ampofila
    Feb 20, 2020 at 14:21
13

User threads continue to run independently of the lifetime of their parent thread, i.e, the creator thread. So, you have to join the threads explicitly by invoking Thread.join before the main thread terminates.

From the Javadoc of Thread:

When a Java Virtual Machine starts up, there is usually a single non-daemon thread (which typically calls the method named main of some designated class). The Java Virtual Machine continues to execute threads until either of the following occurs:

  1. The exit method of class Runtime has been called and the security manager has permitted the exit operation to take place.

  2. All threads that are not daemon threads have died, either by returning from the call to the run method or by throwing an exception that propagates beyond the run method.

If you want JVM to terminate even if a thread t is running, you should make thread t a daemon thread:

t.setDaemon(true);
4
  • I initially focused on answering "Does this mean that every thread has to be joined/killed explicitly for a Java program to terminate?". Then, I expanded it to the the "Why" part. Dec 16, 2012 at 19:35
  • Thanks :) just to make sure I'm not going nuts (I always code joins without thinking in C), if I did this in a C program then it would forcefully terminate the thread, right? Dec 16, 2012 at 19:40
  • No, t.join forces the thread that invokes join to wait until thread t terminates. join has a similar meaning in C (pthreads), but, that's different question. Dec 16, 2012 at 19:47
  • I understand what I join is. I meant that I thought a C app would terminate if a join was not performed whereas a java app keeps running until the threads complete even without the join. But thank you ;) Dec 16, 2012 at 20:15
12

There are two types of threads, user and daemon. The process terminates when there are no more user threads. The main thread is always a user thread. The thread that you start is also a user thread, and therefore keeps the process alive for as long as it runs.

Calling setDaemon(true) on your thread before you start it will make your process terminate (more or less) as soon are your main() function returns.

0
7

The Java Language Specification section 12.8 indicates:

12.8. Program Exit

A program terminates all its activity and exits when one of two things happens:

All the threads that are not daemon threads terminate.

Some thread invokes the exit method of class Runtime or class System, and the exit operation is not forbidden by the security manager.

This means it is not enough for the main thread to finish.

If you do want it to exit when the main thread ends you need to either make the new thread a daemon by using Thread#setDaemon or use Thread#join as you initially suggested.

0

The main thread is also a user thread which is being created and its lifecylce is similar to any other user thread for that matter.
The other user threads are not dependent on the main thread for any reason unless you set the threads as daemon threads. Once the main thread completes its work it ends(it neither ends the other user threads nor will end the process because the other user threads are running).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.