Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how will java handle running threads on exit?

So I'm writing a simple server-client program for school. The client sends a command and some parameters, and the server returns an answer.

The server will listen for new connections, and create a thread for each new client connection. The server listener is also an independent thread that is initiated by main.

The server side Main waits for user input, and quits when it receives the appropriate input.

As it stands, the server listener runs in a loop that says

while(true)
{
 ...
}

So when main reaches the end of the program and goes to exit, will it kill all the running threads? Or will it wait for them to finish running?

If it's the latter case, is there some kind of method i can call that will return true if the system is trying to exit?

Please keep in mind that each component is a part of it's own class.

like image 240
Scuba Steve Avatar asked Dec 26 '22 14:12

Scuba Steve


1 Answers

There are two types of threads: daemon and user. The main thread is always a user thread.

The process is kept alive for as long as there is at least one user thread. When all user threads terminate, all daemon threads are killed and the process terminates.

To set the thread's daemon status, you can call setDaemon() before starting the thread.

So when main reaches the end of the program and goes to exit, will it kill all the running threads? Or will it wait for them to finish running?

If it's a daemon thread, it'll eventually get killed. If it's a user thread, the process will be kept alive for as long as the thread continues to run.

like image 104
NPE Avatar answered Jan 08 '23 20:01

NPE