Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Active threads in ExecutorService

Any ideas how to determine the number of active threads currently running in an ExecutorService?

like image 576
zanussi Avatar asked Sep 17 '08 07:09

zanussi


People also ask

How do I find the active thread count in ExecutorService?

Use a ThreadPoolExecutor implementation and call getActiveCount() on it: int getActiveCount() // Returns the approximate number of threads that are actively executing tasks. The ExecutorService interface does not provide a method for that, it depends on the implementation.

What are active threads?

An active java thread is a thread that is eligible to be the currently running thread of execution. It is a thread that has left the "new" state and has attained (or re-attained) the "runnable" state. Active threads take up residency in the runnable thread pool.

Can threads be submitted to ExecutorService?

We use the Executors. newSingleThreadExecutor() method to create an ExecutorService that uses a single worker thread for executing tasks. If a task is submitted for execution and the thread is currently busy executing another task, then the new task will wait in a queue until the thread is free to execute it.

What is ExecutorService multithreading?

The Java ExecutorService is a construct that allows you to pass a task to be executed by a thread asynchronously. The executor service creates and maintains a reusable pool of threads for executing submitted tasks.


2 Answers

Use a ThreadPoolExecutor implementation and call getActiveCount() on it:

int getActiveCount()  // Returns the approximate number of threads that are actively executing tasks. 

The ExecutorService interface does not provide a method for that, it depends on the implementation.

like image 196
Daan Avatar answered Sep 20 '22 18:09

Daan


Assuming pool is the name of the ExecutorService instance:

if (pool instanceof ThreadPoolExecutor) {     System.out.println(         "Pool size is now " +         ((ThreadPoolExecutor) pool).getActiveCount()     ); } 
like image 26
andyroid Avatar answered Sep 20 '22 18:09

andyroid