Code example for ExecutorService

Methods: awaitTermination, shutdownNow

0
     * Shutdown and await termination. 
     * 
     * @param executorService the executor service 
     */ 
    private void shutdownAndAwaitTermination(ExecutorService executorService) {
        executorService.shutdownNow(); // Disable new tasks from being submitted
        try { 
            // Wait a while for existing tasks to terminate 
            if (!executorService.awaitTermination(5, TimeUnit.SECONDS)) {
                executorService.shutdownNow(); // Cancel currently executing tasks
                // Wait a while for tasks to respond to being cancelled 
                if (!executorService.awaitTermination(5, TimeUnit.SECONDS)) {
                    System.err.println("ExecutorService did not terminate: " + executorService);
                } 
            } 
        } catch (InterruptedException ie) {
            // (Re-)Cancel if current thread also interrupted 
            executorService.shutdownNow();
            // Preserve interrupt status 
            Thread.currentThread().interrupt();
        } 
    }