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

 

原创文章,作者:奋斗,如若转载,请注明出处:https://blog.ytso.com/15889.html

(0)
上一篇 2021年7月19日
下一篇 2021年7月19日

相关推荐

发表回复

登录后才能评论