繁体   English   中英

从执行程序服务池(JAVA)中查找等待线程的作业数?

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

就像建议一样,请使用ThreadPoolExecutor而不是ExecutorService。 您可以利用ThreadPoolExecutor类中存在的阻塞队列。 这将为您提供等待线程的数量。

ThreadPoolExecutor类还具有一些方法来获取已提交任务和已执行任务的计数。

请参阅

线程池执行器

阻塞队列

希望这可以帮助

我建议保留添加到池中的任务的计数器和池完成/启动的任务的计数器。 简单并且适用于任何线程范例。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM