eric
eric

Reputation: 2759

Just how 'approximate' is ThreadPoolExecutor#getActiveCount()?

The javadocs for ThreadPoolExecutor#getActiveCount() say that the method "Returns the approximate number of threads that are actively executing tasks."

What makes this number approximate, and not exact? Will it over or under-report active threads?

Here is the method:

/**
 * Returns the approximate number of threads that are actively
 * executing tasks.
 *
 * @return the number of threads
 */
public int getActiveCount() {
    final ReentrantLock mainLock = this.mainLock;
    mainLock.lock();
    try {
        int n = 0;
        for (Worker w : workers)
            if (w.isLocked())
                ++n;
        return n;
    } finally {
        mainLock.unlock();
    }
}

Upvotes: 6

Views: 1244

Answers (1)

biziclop
biziclop

Reputation: 49744

The method takes the worker list and counts the workers that are being locked.

By the time counting reaches the end of the list, some of the workers previously counted may have finished. (Or some unused workers may have been given a task.)

But you shouldn't be relying on this knowledge as a client, just the fact that it's a best effort approximation. Note that this "inaccuracy" isn't a result of sloppy implementation, it's inherent in every truly multi-threaded system. In such systems there's no global moment of "present". Even if you stop all the workers to count them, by the time you return the result, it may be inaccurate.

Upvotes: 12

Related Questions