Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

multithread exception handling free resources

I'm trying to handle all exceptions generated in a multithreaded problem so as to eliminate memory leaks, interrupted or execution exceptions (I do not want to propagate them) and similar. In the event that I interrupt a thread (Thread.currentThread().interrupt()), is shutdownNow() redundant in the finally below?

ThreadPoolExecutor service = new ThreadPoolExecutor(coreSize, maxSize);

// do stuff

try {               
    List<Future<?>> futures = new ArrayList<Future<?>>();

    for (Item item : items) {
        // processing logic
        Runnable myTask = new MyTask();
        futures.add(service.submit(myTask));
    }

    for (Future<?> f : futures) {
        f.get();
    }
} catch (Exception e) {
    // todo
} finally {
    service.shutdown();
    try {
        service.awaitTermination(duration, TimeUnit.SECONDS);
    } catch (Exception e) {
        // todo
        Thread.currentThread().interrupt();
    } finally {
        if (!service.isTerminated()) {
            service.shutdownNow();
        }
    }
}
like image 665
geco17 Avatar asked Sep 19 '25 00:09

geco17


2 Answers

shutdownNow will behave the same way as shutdown if a MyTask ignore any interruptions. In this case, yes, shutdownNow is redundant.

On the other hand, if the interruption can affect a MyTask, then shutdownNow is necessary for stopping working threads.

like image 51
Andrew Tobilko Avatar answered Sep 21 '25 14:09

Andrew Tobilko


It is redundant only when:

  • All running tasks are not interruptable.
  • And there is no cached task in the blocking queue.

Call shutdown will make the executor not accept new tasks, but the tasks cached in the blocking queue will still be executed.

Call shutdownNow will

  • interrupt all tasks that are running
  • cancel all tasks in the queue
like image 26
xingbin Avatar answered Sep 21 '25 13:09

xingbin