[英]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.