Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to kill Java thread when it is finished?

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.

Here is my code:

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)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading