我有一个服务,我想将其实现为 Google Guava 服务
。
该服务主要运行 while (true)
循环,在事件到达 BlockingQueue
时处理事件。此处提供了简化的示例代码:
https://gist.github.com/3354249
问题在于 BlockingQueue#take()
上的代码阻塞,因此停止服务的唯一方法是中断其线程。这可能使用 Guava 的 AbstractExecutionThreadService
吗?
当然,在这种情况下,我可以使用 queue.poll(1, TimeUnit.SECONDS)
将 queue.take()
替换为轮询循环,从而删除需要线程中断。然而:
出于性能和代码可读性的原因,我想避免这样做
还有其他情况无法避免线程中断,例如如果服务在从
InputStream
读取字节时被阻塞。
最佳答案
您可以覆盖 executor()
方法来提供您自己的执行器,然后它将对线程的引用存储到您的字段中。然后,如果需要,您可以轻松地中断线程。
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicReference;
import com.google.common.util.concurrent.AbstractExecutionThreadService;
public abstract class InterruptibleExecutionThreadService extends AbstractExecutionThreadService {
private final AtomicReference<Thread> runningThread = new AtomicReference<Thread>(null);
@Override
protected Executor executor() {
return new Executor() {
@Override
public void execute(Runnable command) {
Thread thread = Executors.defaultThreadFactory().newThread(command);
runningThread.compareAndSet(null, thread);
try {
thread.setName(serviceName());
} catch (SecurityException e) {
// OK if we can't set the name in this environment.
}
thread.start();
}
};
}
protected void interruptRunningThread() {
Thread thread = runningThread.get();
if (thread != null) {
thread.interrupt();
}
}
}
关于java - 需要中断的服务可以使用Guava的AbstractExecutionThreadService吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11962809/