有时我的服务器收到的请求可能会导致提交 1000 个任务。使用线程池时,我不希望同一请求的任务使用线程池中超过 15 个线程。
如果我不这样做,就会导致其他请求匮乏。
关于如何实现这一点的任何建议。
最佳答案
创建过多请求有两种情况:
您的系统确实需要处理如此多的请求。如果是这种情况,那就别无选择,只能尝试获得更好的硬件并调整各个任务的性能。
您的任务实际上可以合并(我闻到您的情况就是如此)。如果是这种情况,您可以尝试我在下面得到的工作程序,它保证根据将任务放入
ExecutorService
的许多请求,仅触发 1 次执行。 IDispatcher 本质上是我的一个ExecutorService
。
/**
* This class ensures the given task is only dispatched once in the dispatcher.
*
* @author Alex Suo
*
*/
public class DispatchOnceWorker implements IDispatchWorker {
/** Logger of the class. */
private static final Logger LOG = LoggerFactory.getLogger(DispatchOnceWorker.class);
/** The key of task. */
private final String key;
/** The actual task to be dispatched. */
private final Runnable taskWrapper;
/** The dispatcher working on. */
private final IDispatcher dispatcher;
/** The counter for task scheduling count. */
private final AtomicInteger counter = new AtomicInteger();
/**
* Constructor.
*
* @param key The dispatcher key for the task.
* @param task The actual task to be executed/dispatched.
* @param dispatcher The dispatcher working on.
*/
public DispatchOnceWorker(final String key, final Runnable task, final IDispatcher dispatcher) {
this.key = key;
this.dispatcher = dispatcher;
this.taskWrapper = new Runnable() {
@Override
public void run() {
try {
counter.set(1);
task.run();
} catch (Exception e) {
LOG.error("Error executing on dispatch key " + key, e);
} finally {
if (counter.decrementAndGet() > 0) {
dispatcher.dispatch(key, this);
}
}
}
};
}
@Override
public void dispatch() {
if (counter.getAndIncrement() == 0) {
dispatcher.dispatch(key, taskWrapper);
}
}
}
关于java - 在Java ExecutorService中如何设置请求消耗的最大线程数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29360870/