Java Spring Coder
Java Spring Coder

Reputation: 1027

how to get currently running threads

I'm using ThreadPoolExecutor to launch the threads which process requests from a blocking queue. In case of queue is empty, all these worker threads are waiting. which makes every thread in this pool is on Wait state.

public ThreadPoolExecutor executor = new ThreadPoolExecutor(
                EngineConfiguration.numberOfSearchTask,
                EngineConfiguration.numberOfSearchTask + 10, 1000,
                TimeUnit.SECONDS, worksQueue, executionHandler);

I have also launched below scheduled executore which tries to get current active threads in the above pool and when it is 0 then it shutdown the pool:

final ScheduledFuture<?> scheduleFuture = scheduler
.scheduleAtFixedRate(new Runnable() {

    @Override
    public void run() {
        int activeThreadCount =   executor.getActiveThreads();
        if (activeThreadCount == 0) { 

SearchTaskRunner.keepRunning.set(false);
                log.warn("shutdown task runner");

            executor.shutdown();

            log.warn("shutdown scheduler");
            scheduler.shutdownNow();




        }
    }
}, 10, 10000, TimeUnit.SECONDS);

The problem is that after 10 seconds, the scheduler thread gets activeThreadCount=0 and hence shutdown the pools.

we know that:

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

This might not give the accurate number of threads are in active state.

is there anyway I get to know if all my threads from first pool are in wait state?

Upvotes: 1

Views: 8190

Answers (2)

Bhaskara Arani
Bhaskara Arani

Reputation: 1657

Use this code to get all running threads and convert set into array

Set<Thread> tSet = Thread.getAllStackTraces().keySet();
Thread[] tArray = tSet.toArray(new Thread[tSet.size()]);

Upvotes: 0

PSR
PSR

Reputation: 40318

use this

Set<Thread> threadSet = Thread.getAllStackTraces().keySet();

Upvotes: 3

Related Questions