java - 需要中断的服务可以使用Guava的AbstractExecutionThreadService吗?

标签 java service guava interrupt

我有一个服务,我想将其实现为 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/

相关文章:

java - 何时在 Websphere Commerce 中使用访问 bean 或数据 bean?

java - 安卓动画菜单背景

java - 如何处理java URI密码中的 "@"?

android - Android GCM 推送通知 App 中的服务

java - 尝试在 Go 中实现 Java Guava sets.difference

java - 如何在java中测试这个void方法?

javascript - 如何用NSIS打包nodejs并安装一个windows服务?

lambda - 将 CustomObject 列表转换为 Guava Table 集合,复杂性较低

Java三种属性,存储+排序的最佳方式