Home > Blockchain >  How to find the number of active threads and free threads in the thread pool for ScheduledExecutorSe
How to find the number of active threads and free threads in the thread pool for ScheduledExecutorSe

Time:04-02

We are using ScheduledExecutorService for our project and I would like to know how to find the number of free threads available in the thread pool before executing some functions.

private static final ScheduledExecutorService executor;

executor = Executors.newScheduledThreadPool(16);

public void scheduleTask(){

//I want to check the number of free threads or number of active threads in thread pool so that I can schedule jobs accordingly

executor.scheduleAtFixedRate(this, 0, 2, TimeUnit.HOURS);

I tried and found that there are some methods to find the number of active threads for ThreadPoolExecutor but couldn't find any for ScheduledExecutorService

CodePudding user response:

You can use the Thread.activeCount() method, to get the total amount of active Threads.

CodePudding user response:

ScheduledExecutorService is an abstract interface, it is not really related to threads. It can be backed by some other mechanism than threads.

You need to use its specific implementation based on threads, which is ScheduledThreadPoolExecutor. I think in your case it is safe to assume that Executors.newScheduledThreadPool() returns exactly this type:

val executor = Executors.newScheduledThreadPool(16) as ScheduledThreadPoolExecutor
println(executor.activeCount)
  • Related