為ExecutorService增加shutdown hook

FrankYou發表於2018-11-19

 

public class ShutdownHook {
    private static final ShutdownHook INSTANCE = new ShutdownHook();

    private List<ExecutorService> executorServices = Lists.newArrayList();
    private AtomicBoolean closed = new AtomicBoolean(false);

    public static ShutdownHook getInstance() {
        return INSTANCE;
    }

    private ShutdownHook() {
        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                shutdown();
            }
        });
    }

    @PreDestroy
    public void shutdown() {
        if (!closed.compareAndSet(false, true)) {
            return;
        }
        for (ExecutorService executorService : executorServices) {
            tryShutdownNow(executorService);
        }
    }

    private void tryShutdownNow(ExecutorService executorService) {
        try {
            executorService.shutdownNow();
        } catch (Throwable e) {
            //ignore logger maybe has been destroyed
        }

        try {
            executorService.awaitTermination(1, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            //ignore logger maybe has been destroyed
        }
    }

    /**
     * 註冊executorService
     *
     * @param executorService
     */
    public ExecutorService register(ExecutorService executorService) {
        this.executorServices.add(executorService);
        return executorService;
    }
}

 

相關文章