Handling the Hanging Tasks
<p>This is just an example to explain my problem...</p>

<p>I am using ExecutorService with 20 active threads and 75K max queued items...</p>

<p>In my case, a normal task should not take more than 10 seconds, if it takes more time that means there's some problem with the task.</p>

<p>If all the threads are hung due to problematic tasks my RejectionHandler would restart the entire service.</p>

<p>I have two questions here:</p>

<blockquote>
  <ol>
  <li><p>I do not like the idea of restarting the service, instead if there's
  way to detect hanging thread and we could just restart that hung
  thread that would be great. I have gone through couple of articles to handle hung threads with ThreadManager but have not found anything
  with ExecutorService.</p></li>
  <li><p>I am very much fascinated about the <code>Executors.newCachedThredPool()</code>
  because on peak days we are heavily loaded with incoming tasks, and
  on other days they are very few. Any suggestions would be greatly
  appreciated.</p></li>
  </ol>
</blockquote>

<pre><code>   public class HangingThreadTest {

    // ExecutorService executorService = Executors.newCachedThreadPool()
    private static ExecutorService  executorService = new ThreadPoolExecutor(10,
            20, 5L, TimeUnit.SECONDS, new LinkedBlockingQueue&lt;Runnable&gt;(75000));

    public static void main(String... arg0) {
        for (int i = 0; i &lt; 50000; i++) {

            executorService.submit(new Task());
        }
    }

}

/**
 * Task to be completed
 */
class Task implements Runnable {

    private static int count = 0;

    @Override
    public void run() {

        count++;
        if (count%5 == 0) {
            try {
                System.out.println("Hanging Thread task that needs to be reprocessed: "
                        + Thread.currentThread().getName()+" count: "+count);
                Thread.sleep(11000);
            } catch (InterruptedException e) {
                // Do something
            }
        }
        else{
            System.out.println("Normal Thread: "
                    + Thread.currentThread().getName()+" count: "+count);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                //Do something
            }
        }

    }

}
</code></pre>