Reputation:
The ThreadPoolExecutor class in the Java SE 6 docs has the following method:
public int getActiveCount()
Returns the approximate number of threads that are actively executing tasks.
What is the meaning of approximate and actively executing here?
Is there any guarantee that, if before, during and after the call to getActiveCount()
the integer returned by getActiveCount()
will be exactly N?
If getActiveCount()
does not provide this guarantee, is there any other way to obtain this information in a more precise manner?
Prior SO Questions:
I have looked at Thread Pool Executor Monitoring Requirement and How to tell if there is an available thread in a thread pool in java, but they do not answer my queries.
Upvotes: 8
Views: 13877
Reputation: 21815
I think you're possibly confusing things by introducing a notion of "rejoining the pool" that doesn't really exist in the implementation of ThreadPoolExecutor.
Each worker thread sits continually waiting for a task (it effectively sits on top of a blocking queue). Each a task comes in to its queue, that worker is "locked", then any pre-task housekeeping is run, then the actual task is run, then post-task housekeeping, then the worker is "unlocked".
activeCount() gives you the number of threads in the "locked" state: notice that this means that they could actually be conducting 'housekeeping' at the precise moment of calling activeCount(), but that to be counted as 'active', there must be a task actually involved, either about to be, currently, or having just been executed.
Whether that equates with your notion of "rejoining the pool" I'm not sure-- as I say, you seem to be inventing a notion that strictly speaking doesn't exist from the point of view of ThreadPoolExecutor.
Upvotes: 2
Reputation: 76918
The reason that it is approximate is because the number could change during the calculation; you're multi-threading. Before the calculation completes a different number of threads could now be active (A thread that was inactive when checked is now active).
When you say "particular time instance" ... that doesn't really mean anything. The calculation isn't instantaneous. The number you get back is the best possible answer given the fluid/dynamic nature of the pool.
If by chance the calculation starts and completes while none of the threads in the pool change state, then yes that number is "exact" but only until a thread in the pool changes state, which means it might only be "exact" for 1ms (or less).
Upvotes: 10