Is there any way to know at a given point in time how many runnables are waiting to be executed by the ExecutorService
. For example, assuming that the loop is invoking the execute method faster than the runnable can complete and a surplus accumulates, is there anyway to get a running count of the accumulated runnables?
ExecutorService es = Executors.newFixedThreadPool(50);
while (test) {
es.execute(new MyRunnable());
}
Is there any way to know at a given point in time how many runnables are waiting to be executed by the ExecutorService.
Yes. Instead of using the Executors...
calls, you should instantiate your own ThreadPoolExecutor
. Below is what the Executors.newFixedThreadPool(50)
is returning:
ThreadPoolExecutor threadPool = new ThreadPoolExecutor(50, 50,
0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>());
Once you have the ThreadPoolExecutor
, it has a number of getter methods that give you data on the pool. The number of outstanding jobs should be:
threadPool.getQueue().getSize();
Also available from ThreadPoolExecutor
are:
getActiveCount()
getCompletedTaskCount()
getCorePoolSize()
getLargestPoolSize()
getMaximumPoolSize()
getPoolSize()
getTaskCount()
If you want to throttle the number of jobs in the queue so you don't get too far ahead, you should use a bounded BlockingQueue
and the RejectedExecutionHandler
. See my answer here: Process Large File for HTTP Calls in Java
You can use ThreadPoolExecutor
implementation and call toString()
method.
Returns a string identifying this pool, as well as its state, including indications of run state and estimated worker and task counts.
Read more here
There are more methods in this implementation to get you different type of counts.
You can use following two methods:
public long getTaskCount()
Returns the approximate total number of tasks that have ever been scheduled for execution. Because the states of tasks and threads may change dynamically during computation, the returned value is only an approximation.
public long getCompletedTaskCount()
Returns the approximate total number of tasks that have completed execution. Because the states of tasks and threads may change dynamically during computation, the returned value is only an approximation, but one that does not ever decrease across successive calls.
Cheers !!