簡體   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