简体   繁体   English

具有正在运行的任务数的ExecutorService

[英]ExecutorService with number of running tasks

I want to get the number of tasks that are submitted to an executor service and not yet finished (ie currently running/active or queued). 我想获得提交给执行程序服务但尚未完成的任务数(即当前正在运行/活动或排队)。 Executor service does not have an inbuilt method for this. Executor服务没有内置的方法。

((ThreadPoolExecutor) executorService).getActiveCount()

This "Returns the approximate number of threads that are actively executing tasks." 这“返回正在执行任务的大致线程数”。

Is this a valid alternative to maintaining, say, a volatile counter ? 这是维持一个易变的计数器的有效替代方案吗? Why is it approximate ? 为什么它是近似的? Will I actually be better off maintaining a counter ? 我真的会更好地维持一个柜台吗? Why does executor service not have an in-built method for this ? 为什么执行程序服务没有内置方法呢?

Let's look at the task: It would only be possible to tell you the exact number, if you halt the system, count, return, start the system. 让我们来看看这个任务:只有你可以告诉你确切的数字,如果你停止系统,计数,返回,启动系统。 Otherwise: During counting, threads may start and end, so the number is an approximation. 否则:在计数期间,线程可能会开始和结束,因此数字是近似值。

See the implementation in OpenJDK8: 请参阅OpenJDK8中的实现:

1812    public int More ...getActiveCount() {
1813        final ReentrantLock mainLock = this.mainLock;
1814        mainLock.lock();
1815        try {
1816            int n = 0;
1817            for (Worker w : workers)
1818                if (w.isLocked())
1819                    ++n;
1820            return n;
1821        } finally {
1822            mainLock.unlock();
1823        }
1824    }

The implementation is straight forward, but it is like counting ants without killing them: They will come and go while you count. 实施是直截了当的,但它就像计算蚂蚁而不杀死它们:它们会在你数数的时候来去匆匆。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM