在我编写的web服务器中,每个请求都会调用一个操作列表。其中一些操作并不像其他操作那样关键,所以我想在后台线程中运行它们。
此外,由于它们不是那么重要,我不关心它们中的一个是否会罕见地失败,我也不希望它们永远占用一个线程,所以其他线程将可用于处理下一批处理。
因此,我希望有一个线程池(例如: 10个线程),并像这样向每个后台任务分发一个线程。将每个线程限制在1秒内,如果在此时间内它还没有完成,就干掉它,并为下一个任务做好准备。
我该怎么做呢?
到目前为止,我得到的是:
public class AsyncCodeRunner {
private static final ExecutorService executor = Executors.newFixedThreadPool(10);
public void Run(Callable<Void> callableCode, int timeout) {
final int threadTimeout = 10;
Future<Void> callableFuture = executor.submit(callableCode);
try {
callableFuture.get(threadTimeout, TimeUnit.SECONDS);
} catch (Exception e) {
logger.Info("Thread was timed out", e);
}
}
}
我想像这样使用这个类:
public void processRequest(RequestObject request) {
// do some important processing
// throw some less important processing to background thread
(new AsyncCodeRunner()).Run(new Callable<Void> () {
@Override
public Void call() throws Exception {
// do something...
return null;
}
}, 1); // 1 second timeout
// return result (without waiting for background task)
return;
}
这会像我想要的那样工作吗?或者,我应该如何更改它,使其有效?
如果我调用了Run()
,但是线程池中没有可用的线程可供分配,会发生什么呢?
https://stackoverflow.com/questions/28108022
复制相似问题