I'd like to log the number of active threads created by a newCachedThreadPool call. I can't seem to find out where to get this value though.
+2
A:
You can pass a ThreadFactory
to newCachedThreadPool
Let it implement some logging when creating a new Thread, since newCachedThreadPool reuses threads you don't have to worry about threads end.
OR
Cast the executor into a ThreadPoolExecutor
and call its getPoolSize()
method
Guillaume
2010-04-17 08:25:08
The cached thread pool will end threads that have not been used recently. Therefore, the custom `ThreadFactory` can only keep track of how many threads have been created not how many are active.
Matthew T. Staebler
2010-04-17 08:27:53
Be aware that casting the `ExectuorService` returned by `newCachedThreadPool` is not guaranteed to by a `ThreadPoolExecutor` in all implementations of Java. With that being said, that may very well be a risk that you are willing to take.
Matthew T. Staebler
2010-04-17 08:45:08
A:
I am not sure whether you are interested in the number of threads that exist or whether you are interested in the number of tasks that are active. If you are interested in the tasks, then you can store a Future
for each task that has been added. When you want to know how many tasks are active, you can simply count the number of Future
objects that respond false
to isDone
. The ones that respond true
can obviously be removed at that point.
Matthew T. Staebler
2010-04-17 08:36:19