Search code examples
javamultithreadingthread-safetyexecutorservicethreadpoolexecutor

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();
        }
    }
}

Solution

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