简体   繁体   中英

Logging tasks that were being processed by ExecutorService when it was shut down

I'm working on a Spring Boot application that accepts requests and processes them using an ExecutorService . Each task submitted to the ExecutorService is non-iterative, long-running and is non-interruptible (in essence it submits the request in turn to several other services through a messaging broker, blocks for each of them, and waits for a reply).

I'm trying to implement graceful shutdown of the application in such a way that the application waits for a specified time for the ExecutorService to complete all running tasks and then shuts down. If, after the specified time has lapsed, there are unfinished tasks, I want the application to log the IDs of the tasks.

The relevant code is:

@Service
public class Service {

  private ExecutorService es = Executors.newFixedThreadPool(10);

  public handle(MyTask task) {
    es.execute(task);
  }

  @PreDestroy
  void destroy() {
    es.shutdown();
    try {
      boolean terminated = es.awaitTermination(60, TimeUnit.SECONDS);
      if (!terminated) {
      // I want to somehow log the IDs of MyTask's that haven't finished processing
      es.shutdownNow();
    } catch (InterruptedException e) {
      // Should not get here in the existing implementation as MyTask's are non- 
      // interruptible
    }
  }

How do I achieve this? I am contemplating two options but cannot wrap my head around how to implement either of them.

  1. Wrap MyTask into another Runnable that would check in a loop for interruption and, if interrupted, log the id of MyTask . So in essence make MyTask interruptible. How can this be implemented?
  2. Save submitted MyTask s in a collection and on shutdown poll the collection for those that haven't completed and log their IDs. The question here is how do I keep the collection current and remove those MyTask s that have been completed?

To reiterate, I'm implementing graceful shutdown of the whole application, not just the executor service. So the entire app shuts down after the specified period has lapsed. Hence the need to log all tasks that haven't finished processing by the executor service.

I think I might have found an option based on this post: implement an executor service that puts the task into a map and removes it once it's finished processing. Upon shutdown, we iterate over the map and log the tasks that are still there. Some of them might complete between logging and shutting the app down but that false positive is acceptable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM