[英]Find number of jobs waiting for thread from executor service pool (JAVA)?
我有一个服务器,它有多个使用 java executorService 实现的工作线程(即线程池)
我的问题是,如果线程池中没有可用的空闲线程,我无法每秒记录等待处理的作业长度。
注意:日志记录不是我的问题,但我希望能够看到有多少任务/作业正在等待工作线程处理,是否可以查看执行程序服务中等待队列(不是线程池)的长度?
我不知道如何实现这个东西。
ThreadPoolExecutor
构造函数接受一个BlockingQueue
参数,该参数是用于存储等待作业的Queue
实现。 您可以使用getQueue()
方法请求此队列,然后检查队列的大小:
System.out.println("Number of waiting jobs: "+executor.getQueue().size());
请注意,此方法在ExecutorService
接口中不可用,因此最好显式构造ThreadPoolExecutor
而不要使用Executors.newFixedThreadPool
和好友:
ThreadPoolExecutor executor = new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
尽管OpenJDK / OracleJDK中的Executors.newFixedThreadPool
相同,但未指定,因此使用(ThreadPoolExecutor)Executors.newFixedThreadPool(nThreads)
可能会在将来的Java版本或替代JDK实现中导致ClassCastException
。
如果可以假设服务器使用的ExecutorService
实现是ThreadPoolExecutor
,则可以使用方法getQueue()
返回尚未分配给Worker
的任务数。
/**
* Returns the task queue used by this executor. Access to the
* task queue is intended primarily for debugging and monitoring.
* This queue may be in active use. Retrieving the task queue
* does not prevent queued tasks from executing.
*
* @return the task queue
*/
public BlockingQueue<Runnable> getQueue() {
return workQueue;
}
因此,您可以运行以下内容:
if(LOGGER.isDebugEnabled()) {
LOGGER.debug(String.format("Pending tasks: %d", executor.getQueue().size()));
}
我建议保留添加到池中的任务的计数器和池完成/启动的任务的计数器。 简单并且适用于任何线程范例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.