Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
    }
}
like image 1000
eric Avatar asked Jul 17 '14 18:07

eric


People also ask

What is ThreadPoolExecutor?

ThreadPoolExecutor is an ExecutorService to execute each submitted task using one of possibly several pooled threads, normally configured using Executors factory methods. It also provides various utility methods to check current threads statistics and control them.

How does thread pool keeps the thread alive?

The setKeepAliveTime() method of ThreadPoolExecutor class sets the thread keep-alive time, which is the amount of time that threads may remain idle before being terminated.


1 Answers

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.

like image 74
biziclop Avatar answered Sep 18 '22 02:09

biziclop