Reputation: 823
I have written a main application which creates two threads viz A and B. Thread A is user thread and thread B is daemon. A finishes the job and hence the JVM exits but Thread B is still running. Since Threads A and B are created in the JVM space, and JVM has exited since all the user threads have completed execution, where Thread B execute ? In which process space does it execute?
Upvotes: 0
Views: 182
Reputation: 1
Daemon threads are used in background task for example GC or custom use case. And the purpose of daemon threads is to serve User threads and once there is no user threads running and program exit then no use of daemon threads
Upvotes: 0
Reputation: 5223
A "daemon" thread is intended to provide a general service in the background as long as the program is running, but is not part of the essence of the program. Thus, when all of the non-daemon threads complete, the program is terminated "abruptly", killing all daemon threads in the process.
So as soon as all non-daemon exits, the JVM shuts down all the daemons immediately, without any of the formalities you might have come to expect (Not even Finally). Because you cannot shut daemons down in a nice fashion, they are rarely a good idea.
Non-daemon Executors are generally a better approach, since all the tasks controlled by an Executor can be shut down at once.
Now Coming to your particular scenario.
A finishes the job and hence the JVM exits but Thread B is still running- This Assumption is wrong B is not running
where Thread B execute ? In which process space does it execute?
B Will be terminated "abruptly" as soon as A is finished so it not in execution now and hence no question of process space.
Upvotes: 2