Search code examples
javaexecutorservicethreadpoolexecutor

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 (i.e currently running/active or queued). Executor service does not have an inbuilt method for this.

((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 ?


Solution

  • 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:

    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.