java - 在Java ExecutorService中如何设置请求消耗的最大线程数

标签 java multithreading performance

有时我的服务器收到的请求可能会导致提交 1000 个任务。使用线程池时,我不希望同一请求的任务使用线程池中超过 15 个线程。

如果我不这样做,就会导致其他请求匮乏。

关于如何实现这一点的任何建议。

最佳答案

创建过多请求有两种情况:

  1. 您的系统确实需要处理如此多的请求。如果是这种情况,那就别无选择,只能尝试获得更好的硬件并调整各个任务的性能。

  2. 您的任务实际上可以合并(我闻到您的情况就是如此)。如果是这种情况,您可以尝试我在下面得到的工作程序,它保证根据将任务放入 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/

相关文章:

c++ - 多线程环境中的全局数据行为,C++

ios - 什么是iOS sleep 功能

java - 为什么中断方式和 isInterrupted 行为之间存在差异?

c# - 将文件夹移动到 UWP 中另一个位置的最快方法

mysql - 使用 select count(*) 更新查询速度较慢

ruby-on-rails - ruby 1.9.3 中的 Rails 3.0.9 渲染部分性能

java - 投票应用程序的安全性

java - 尝试用问号替换字符串中的字母,但继续用问号替换空格

java - 如何更改通知的内容而不重新创建它?

java - 如何使用 Spring WebClient 进行同步调用?