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/tech/pnotes/15889.html