gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 19:34:22 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com