title: Using UncaughtExceptionHandler effectively
body: <p>I got to know about this Java 1.5 capability recently and I developed a sample code to use this. My objective is to restart the thread when it gets dead due to an uncaught exception.</p>
  
  <pre><code>public class ThreadManager {
  
      public static void main(String[] args) throws InterruptedException {
          startThread();
      }
  
      public static void startThread(){
          FileReaderThread reader = new FileReaderThread("C:\\Test.txt");
          Thread thread = new Thread(reader);
          thread.setUncaughtExceptionHandler(new CustomExceptionHandler());
          thread.start();
      }
  }
  </code></pre>
  
  <p>Here the file reader is just contains a routine to read a file and print contents. I am simulating an uncaught exception by making the file name null inside that class.</p>
  
  <p>Then my CustomExceptionHandler class is as follows.</p>
  
  <pre><code>public class CustomExceptionHandler implements Thread.UncaughtExceptionHandler {
  
      public void uncaughtException(Thread t, Throwable e) {
          ThreadManager.startThread();
      }
  }
  </code></pre>
  
  <p>But here I observed a problem. After the uncaught exception the thread is in Sleeping state. I verified it by using a profiler. So creating new threads would fillup my memory with time. Making system.gc() followed by a t = null didn't work.</p>
  
  <p>So what is the best approach you suggest to deal with this scenario? I just need a new thread and I don't want any older threads any more.... </p>
  
  <p>Thanks</p>