Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can i spawn a thread from a servlet?

I would like to ask a basic question before i get on to my main question .

Lets say i am running a simple Java program, which spawns a thread in the main function. Will the thread continue to run when the main function completes? Is there a concept of parent/child relationships between threads.

I have a servlet which takes a long while to process a request (5 mins). Can i spawn a background thread from the main servlet to handle the work & return soon. Would the background thread keep running even when the main servlet has finished processing?

like image 395
Pramanat Avatar asked Jan 29 '11 10:01

Pramanat


1 Answers

When you want your application to exit even though you still have running threads, you have to mark your thread as a daemon thread:

Thread t = new Thread(myRunnable);
t.setDaemon(true),
t.start();

This is especially important when you do that in an application server, otherwise the server cannot be shut down!

If you do that repeatedly you might want to consider a ThreadPool to make this more efficient

like image 116
a_horse_with_no_name Avatar answered Sep 21 '22 22:09

a_horse_with_no_name