Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Number of active tasks using ThreadPoolExecutor

I am using a ThreadPoolExecutor to execute tasks in my Java application. I have a requirement where I want to get the number of active tasks in the queue at any point in time in the executor queue . I looked up at the javadoc for ThreadPoolExecutor and found two relevant methods: getTaskCount() and getCompletedTaskCount().

Per the documentation, I could get the number of scheduled tasks and completed tasks from the above two methods respectively. But I am not able to find a solution for getting the number of active tasks in the queue at any point in time. I can do something like:

getTaskCount() = getCompletedTaskCount() + failed tasks + active tasks

But the number of failed tasks is not directly available to arrive at the intended calculation.

Am I missing something here ?

like image 355
invinc4u Avatar asked Apr 06 '11 20:04

invinc4u


1 Answers

I don't think you need to know the failed count with the calculation you're trying to use.

long submitted = executor.getTaskCount();
long completed = executor.getCompletedTaskCount();
long notCompleted = submitted - completed; // approximate

Would be (approximately) sufficient.


Alternatively, you can use getQueue() with size():

int queued = executor.getQueue().size();
int active = executor.getActiveCount();
int notCompleted = queued + active; // approximate

This answer presumes you're looking for a "not yet completed" count. Your question contradicts itself so I'm not completely certain what you're asking. Reply to my comment on your question if this is incorrect, and I'll update this answer accordingly.

like image 117
Rob Hruska Avatar answered Oct 21 '22 17:10

Rob Hruska