static-max
static-max

Reputation: 789

List all running/queued threads in ThreadPoolTaskExecutor

I use a ThreadPoolTaskExecutor in Spring to schedule my tasks.

Is there a way to get a list or something of every running and queued thread of that task executor/pool?

Upvotes: 9

Views: 9002

Answers (3)

Fengzmg
Fengzmg

Reputation: 768

One possible way is to use Reflection or Spring provided ReflectionUtils or ReflectionTestUtils..

I used ReflectionTestUtils in my Junit to test the scenario when one or more sleeping thread is interrupted.

The code snippet is:

Collection<Object> workers = (Collection<Object>) ReflectionTestUtils.getField(responseHandlerTaskExecutor.getThreadPoolExecutor(), "workers");

for(Object worker : workers){
    Thread workerThread = (Thread)ReflectionTestUtils.getField(worker, "thread");
    workerThread.interrupt();
}

Upvotes: 0

static-max
static-max

Reputation: 789

Maybe not very elegant, but this way I can get all threads from a known Executor (using the startsWith() prefix).

Set<Thread> threadSet = Thread.getAllStackTraces().keySet();
for (Thread thread : threadSet) {
  if (thread.getName().startsWith("MyExecutor")) {
  System.out.println(thread.getName() + " " + thread.getState());
    for (StackTraceElement s : thread.getStackTrace()) {
      System.out.println(s);
    }
  }
}

Thanks to Surveon for his hint, I upvoted for his approch to get the queued threads.

Upvotes: 6

Surveon
Surveon

Reputation: 723

It looks like you can get at the underlying ThreadPoolExecutor by calling getThreadPoolExecutor.

This would allow you to access the queue, at the very least.

Upvotes: 0

Related Questions