Home > Net >  How to kill Java thread when it is finished?
How to kill Java thread when it is finished?

Time:11-20

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)

CodePudding user response:

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.

CodePudding user response:

Use @Async

In a Web Application, creating Threads manually isn't the right way to go. This process is constful, and it's better to maintain a Pool of Threads.

Since you're using Spring Boot, everything you need is annotate the configuration class with @EnableAsync and ThreadPoolTaskExecutor would be configured for you under the hood. You can customize it via application.properties (for instance, specify the required min/max pool size).

And to tell that a certain method should be executed in a different Thread, you need to place annotation @Async on it (note that this method should reside in a class managed by Spring, i.e. annotated with one of the stereotype annotations @Component, @Controller, etc.).

@Async
public Advert saveAdvert(Advert advert) {
    Advert advertToSave = advertRepository.save(advert);

    try {
        populateAdvertSearch(advertToSave);
    } catch (ParseException e) {
        e.printStackTrace();
    } catch (OfficeNotFoundException e) {
        e.printStackTrace();
    } catch (OfficePropertyNotFoundException e) {
        e.printStackTrace();
    }
    
    return advertToSave;
}

CodePudding user response:

Well, it's not a good idea to terminate a running thread from the outside, but if you want so, you can use ExecutorService.

Let's say you want to kill specific thread after 5 seconds;

if (executor.awaitTermination(5, TimeUnit.SECONDS)) {
  // continue
} else {
  // force shutdown
  executor.shutdownNow();
}
  • Related