Java: awaiting termination

 

        final ExecutorService executor = Executors.newCachedThreadPool();
        try {
            Future task = executor.submit(() -> {
                doSomething();
            });
            executor.shutdown();
            executor.awaitTermination(timeoutInMinutes, TimeUnit.MINUTES);

            SomeResult result = task.get();

            return Optional.of(result);
        } catch (InterruptedException | ExecutionException e) {
            if (!executor.isShutdown()) {
                executor.shutdownNow();
            }
            Thread.currentThread().interrupt();
        } finally {
            log.debug("Shutting down the service executor");
            if (!executor.isShutdown()) {
                executor.shutdownNow();
            }
        }
Advertisements