我正在使用从AbstractScheduledService
继承的一些服务,这些服务由ServiceManager
管理。一切正常,但是现在有一个服务,其runOneIteration
需要相当长的时间,结果我的过程花费了太长时间才能终止(超过五秒钟)。
从AbstractExecutionThreadService
继承的其他服务也有类似的问题,我可以通过解决
@Override
protected final void triggerShutdown() {
if (thread != null) thread.interrupt();
}
并将
private volatile thread
存储在run
方法中。但是,this issue中没有triggerShutdown
的AbstractScheduledService
。我已经考虑过使
runOneIteration
减少工作量的替代方法,但这既丑陋又效率低下。我无法覆盖
stopAsync
,因为它是最终的,看不到其他任何内容。是否有做类似这样的事情的钩子? 最佳答案
你可以用这个吗?您是否有任何理由无法自己添加TriggerShutdown?
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();
}
}
}