为ExecutorService增加shutdown hook

 

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

 

posted @ 2018-11-19 15:22  FrankYou  阅读(480)  评论(0编辑  收藏  举报