How to find the number of runnables waiting to be executed

試著忘記壹切 提交于 2019-12-11 11:29:33

问题


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());
}

回答1:


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




回答2:


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 !!



来源:https://stackoverflow.com/questions/18985691/how-to-find-the-number-of-runnables-waiting-to-be-executed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!