优雅地向ExecutorServices执行队列长度指示符

优雅地向ExecutorServices执行队列长度指示符

本文介绍了优雅地向ExecutorServices执行队列长度指示符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Why, oh why doesn't java.util.concurrent provide a queue length indicators for its ExecutorServices? Recently I found myself doing something like this:

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 通过静态工厂方法获得,因此没有办法简单地扩展其他优秀的单线程执行器和添加队列计数器。那么我应该怎么做:

Which works ok, but... I think this really should be implemented as a part of the ExecutorService. It's dumb and error prone to carry around a counter separated from the actual queue, whose length the counter is supposed to indicate (reminds me of C arrays). But, ExecutorServices are obtained via static factory methods, so there's no way to simply extend the otherwise excellent single thread executor and add a queue counter. So what should I do:


  1. 重新发布已在JDK中实现的内容

  2. 其他聪明的解决方案?


推荐答案

有更直接的方式:

ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newSingleThreadExecutor();
// add jobs
// ...
int size = executor.getQueue().size();

虽然你可能不会使用Executor的方便的创建方法,摆脱铸造,因此确保执行器总是实际上是一个 ThreadPoolExecutor ,即使 Executors.newSingleThreadExecutor 会改变一天。

Although you might consider not to use the convenience create methods of Executor, but rather create the executor directly to get rid of the cast and thus be sure that the executor will always actually be a ThreadPoolExecutor, even if the implementation of Executors.newSingleThreadExecutor would change some day.

ThreadPoolExecutor executor = new ThreadPoolExecutor( 1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>() );

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

This is directly copied from Executors.newSingleThreadExecutor in JDK 1.6. The LinkedBlockingQueue that is passed to the constructor is actually the very object that you will get back from getQueue.

这篇关于优雅地向ExecutorServices执行队列长度指示符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 06:55