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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With