Issue
First time I am working with threads in spring boot webapp and when I do debugging then I see thread names are increasing like Thread-1, Thread-2... for every call method so I thought that the program is not killing the thread but creating new thread for every call.
public Advert saveAdvert(Advert advert) {
Advert advertToSave = advertRepository.save(advert);
new Thread(() -> {
try {
populateAdvertSearch(advertToSave);
} catch (ParseException e) {
e.printStackTrace();
} catch (OfficeNotFoundException e) {
e.printStackTrace();
} catch (OfficePropertyNotFoundException e) {
e.printStackTrace();
}
}).start();
return advertToSave;
}
Here populateAdvertSearch()
is a void method. I just want to do that task independently from the main thread because it is very long and I do not want client to wait whole method so another independent thread will do this void method. But as I said I though that the program is not killing threads. How can I kill the thread or Should I kill explicitly (I am not sure maybe it is already killed after execution is done but then why Intellij IDEA debug showing thread names as increasing)
Solution
After thread starts and run()
method returns, that Thread
will terminate and eventually be garbage collected. You see incrementing id numbers because you are starting new threads for each such action. So no explicit termination is required.
Answered By - KunalVarpe
Answer Checked By - Timothy Miller (JavaFixing Admin)