有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何触发关闭Guava AbstractScheduledService?

我正在使用从AbstractScheduledService继承的一些服务,这些服务由ServiceManager管理。一切正常,但是现在,有一个服务的runOneIteration花费了相当长的时间,因此,我的进程需要太长的时间才能终止(超过5秒)

还有其他从AbstractExecutionThreadService继承的服务,也有类似的问题,我可以通过

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

以及在run方法中存储private volatile thread。但是,正如this issue中所述,AbstractScheduledService没有triggerShutdown

我已经考虑过让runOneIteration做更少的工作这样的替代方案,但它既丑陋又低效

我无法覆盖stopAsync,因为它是最终版本,我看不到任何其他内容<像这样的事情有没有钩子


共 (1) 个答案

  1. # 1 楼答案

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

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