Find the number of jobs waiting for a thread from an artist services pool (JAVA)?

I have a server with several worker threads implemented using java executorService (i.e. thread pool)

My problem is that I cannot log every second, the length of jobs waiting to be processed if there is no free thread in the thread pool.

NOTE. Logging is not my problem, but I want to see how many tasks / jobs are waiting to be processed by the workflow, anyway, to see the length of the wait queue (and not the thread pool) inside the executing service?

I do not know how to implement this thing.

+5
source share
3 answers

The ThreadPoolExecutor constructor accepts the BlockingQueue parameter, which is the Queue implementation used to store pending jobs. You can request this queue using the getQueue() method, and then check the size of the queue:

 System.out.println("Number of waiting jobs: "+executor.getQueue().size()); 

Please note that this method is not available in the ExecutorService interface, therefore it is better to build ThreadPoolExecutor explicitly instead of using Executors.newFixedThreadPool and friends:

 ThreadPoolExecutor executor = new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>()); 

While Executors.newFixedThreadPool in OpenJDK / OracleJDK does the same, it is not specified, so using (ThreadPoolExecutor)Executors.newFixedThreadPool(nThreads) may lead to a ClassCastException in future versions of Java or alternative JDK implementations.

+12
source

If you can assume that the ExecutorService implementation used by your server is ThreadPoolExecutor , you can use the getQueue() method, which returns the number of tasks that have not yet been assigned to 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; } 

So you can run something like this:

  if(LOGGER.isDebugEnabled()) { LOGGER.debug(String.format("Pending tasks: %d", executor.getQueue().size())); } 
+3
source

Like a sentence, use ThreadPoolExecutor instead of ExecutorService. You can use the blocking queue present in the ThreadPoolExecutor class. This will give you the number of pending threads.

Also, the ThreadPoolExecutor class has methods for getting the number of submitted tasks and completing the task.

Talk to

ThreadPoolExecutor

Blockingquueue

Hope this helps

0
source

Source: https://habr.com/ru/post/1234523/


All Articles