Ganesh91
Ganesh91

Reputation: 31

Is there a way to find hanging or stuck threads in executor service?

Is there a way to find hanging or stuck threads in executor service thread pool? or Is there a way to find if all threads in executor service is hanging or stuck, so we could shutdown or restart executor service?

Stuck or hanging means, All Threads in executor service might be with Waiting state for long time without doing anything. So no more threads to process other waiting tasks in executor service in such scenarios

Upvotes: 0

Views: 1035

Answers (1)

0xDEADBEEF
0xDEADBEEF

Reputation: 590

If you know how long the task will be running you can use Future#get to timeout the task so that it will not get stuck.

One example is supposed we want to run X number of task

/*
   spawn one thread only wait for each task to finish
*/
ExecutorService executorService=Executors.newSingleThreadExecutor();
List<Runnable> runnables = ... ;
for(Runnable task : runnables)
{
  Future<?> future=executor.submit(task);
  try
  {
   future.get(2,TimeUnit.SECONDS); // exit task in 2 seconds
  }
  catch(Exception ex)
  {
    ex.printStackTrace();
  }
}

Upvotes: 1

Related Questions