代码之家  ›  专栏  ›  技术社区  ›  maaartinus

如何关闭Guava AbstractScheduledService?

  •  3
  • maaartinus  · 技术社区  · 6 年前

    我正在使用从 AbstractScheduledService ,由 ServiceManager runOneIteration 需要相当长的时间,因此,我的进程需要很长时间才能终止(超过5秒)。

    有其他服务继承自 AbstractExecutionThreadService ,有一个类似的问题,我可以通过

    @Override
    protected final void triggerShutdown() {
        if (thread != null) thread.interrupt();
    }
    

    private volatile thread run 方法。但是,没有 triggerShutdown 抽象调度服务 如中所述 this issue .

    跳动 少做些工作,但既难看又低效。

    stopAsync

    1 回复  |  直到 6 年前
        1
  •  2
  •   Charles    6 年前

    你能用这个吗?有什么原因你不能自己添加触发器吗?

    class GuavaServer {
        public static void main(String[] args) throws InterruptedException {
            GuavaServer gs = new GuavaServer();
            Set<ForceStoppableScheduledService> services = new HashSet<>();
            ForceStoppableScheduledService ts = gs.new ForceStoppableScheduledService();
            services.add(ts);
            ServiceManager manager = new ServiceManager(services);
            manager.addListener(new Listener() {
                public void stopped() {
                    System.out.println("Stopped");
                }
    
                public void healthy() {
                    System.out.println("Health");
                }
    
                public void failure(Service service) {
                    System.out.println("Failure");
                    System.exit(1);
                }
            }, MoreExecutors.directExecutor());
    
            manager.startAsync(); // start all the services asynchronously
            Thread.sleep(3000);
            manager.stopAsync();
            //maybe make a manager.StopNOW()?
            for (ForceStoppableScheduledService service : services) {
                service.triggerShutdown();
            }
        }
    
        public class ForceStoppableScheduledService extends AbstractScheduledService {
    
            Thread thread;
    
            @Override
            protected void runOneIteration() throws Exception {
                thread = Thread.currentThread();
                try {
                    System.out.println("Working");
                    Thread.sleep(10000);
                } catch (InterruptedException e) {// can your long process throw InterruptedException?
                    System.out.println("Thread was interrupted, Failed to complete operation");
                } finally {
                    thread = null;
                }
                System.out.println("Done");
            }
    
            @Override
            protected Scheduler scheduler() {
                return Scheduler.newFixedRateSchedule(0, 1, TimeUnit.SECONDS);
            }
    
            protected void triggerShutdown() {
                if (thread != null) thread.interrupt();
            }
        }
    }