优雅地实现 ExecutorServices 的队列长度指示器

2024-03-09

为什么,哦,为什么不java.util.concurrent为其提供队列长度指标ExecutorService是?最近我发现自己在做这样的事情:

ExecutorService queue = Executors.newSingleThreadExecutor();
AtomicInteger queueLength = new AtomicInteger();
...

public void addTaskToQueue(Runnable runnable) {
    if (queueLength.get() < MAX_QUEUE_LENGTH) {
        queueLength.incrementAndGet(); // Increment queue when submitting task.
        queue.submit(new Runnable() {
            public void run() {
                runnable.run();
                queueLength.decrementAndGet(); // Decrement queue when task done.
            }
        });
    } else {
        // Trigger error: too long queue
    }
}

哪个工作正常,但是......我认为这确实应该作为ExecutorService。携带柜台是愚蠢且容易出错的分开来自实际队列,计数器应该指示其长度(让我想起 C 数组)。但,ExecutorService是通过静态工厂方法获得的,因此无法简单地扩展原本优秀的单线程执行器并添加队列计数器。所以我该怎么做:

  1. 重新发明 JDK 中已经实现的东西?
  2. 其他聪明的解决方案?

还有一个更直接的方法:

ThreadPoolExecutor executor = new ThreadPoolExecutor( 1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>() );
// add jobs
// ...
int size = executor.getQueue().size();

这是直接复制过来的Executors.newSingleThreadExecutor在 JDK 1.6 中。这LinkedBlockingQueue传递给构造函数的实际上就是您将从中返回的对象getQueue.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

优雅地实现 ExecutorServices 的队列长度指示器 的相关文章

随机推荐