首页 文章

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

提问于
浏览
7

我有一个服务器,它有多个使用java executorService实现的工作线程(即一个线程池)

我的问题是,如果线程池中没有可用的空闲线程,我无法每秒登录,等待处理的作业长度 .

注意:日志记录不是我的问题,但我希望能够看到工作线程正在等待处理多少个任务/作业,无论如何都要查看执行程序服务中的等待队列(而不是线程池)的长度?

我不知道如何实现这个东西 .

3 回答

  • 14

    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 执行相同操作,但未指定,因此在将来的Java版本或替代JDK实现中使用 (ThreadPoolExecutor)Executors.newFixedThreadPool(nThreads) 可能会导致 ClassCastException .

  • 0

    如果您可以假设服务器使用的 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()));
     }
    
  • 3

    正如建议使用ThreadPoolExecutor而不是ExecutorService . 您可以利用ThreadPoolExecutor类中的阻塞队列 . 这将为您提供等待的线程数 .

    ThreadPoolExecutor类也有方法来获取提交的任务和执行任务的计数 .

    参考

    ThreadPoolExecutor

    BlockingQueue

    希望这可以帮助

相关问题