zoukankan      html  css  js  c++  java
  • 为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;
        }
    }
  • 相关阅读:
    Ruby 操作 Mysql (2)
    有关SQL模糊查询【转载】
    vim命令行大全【转载】
    Ruby连接MySQL
    c# 操作mysql
    sublime 3 快捷键大全
    VS2010快捷键大全
    [使用Xpath对XML进行模糊查询]
    vim永久显示行号
    Ubuntu16.04LTS安装flash player
  • 原文地址:https://www.cnblogs.com/frankyou/p/9983301.html
Copyright © 2011-2022 走看看