Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the number of tasks in a queue in executor service?

So I am using executorservice to create a threadpool.

ExecutorService executor = Executors.newSingleThreadExecutor();

I am trying to access the number of tasks in the queue of the threadpool. I see that there are no methods to get that. I know there are methods to get the queue size in threadpoolexecutor but how can I do that with executorservice object.

Like I said I can get the queue information if I have created a ThreadpoolExecutor like this

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

I know I can use the tpExecutor.queue.size() to get the number of tasks in queue of threadpool. But currently I have declared my threadpool using Executor Service. How can I do that? It would be appreciable if people can write code and demonstrate.

like image 423
africandrogba Avatar asked Sep 02 '17 21:09

africandrogba


1 Answers

I think this should work:

    ThreadPoolExecutor threadPoolExecutor = (ThreadPoolExecutor) this.executorService;
    int activeCount = threadPoolExecutor.getActiveCount();
    long taskCount = threadPoolExecutor.getTaskCount();
    long completedTaskCount = threadPoolExecutor.getCompletedTaskCount();
    long tasksToDo = taskCount - completedTaskCount - activeCount;

For some reason though it does not always exclude all the cancelled tasks, only after some periodic clean ups. So I had to introduce a second counter:

    long tasksToDo2 = threadPoolExecutor.getQueue().stream().filter(t -> !((FutureTask) t).isDone()).count();
like image 58
tanacsg Avatar answered Oct 18 '22 02:10

tanacsg