title: Why UserThread running with ScheduleExecutorService does not get garbage collected
body: <p>Please help me find the reason for Thread leak in the code below. The <code>TestThread</code> does not get garbage collected even after run() has completed (verified from the consoled print statement) and the main method has exited (verified from print statement and profiler tool).</p>
  
  <p>The <code>TestThread</code>, however, gets garbage collected if it is set as a Daemon Thread i.e. <code>t.setDaemon(true)</code>. The code below is just a sample code which illustrates the problem in my application. I'm trying to use some pre-existing scheduling class (which was designed by someone else using <code>ScheduledExecutorService</code>). I notice that when I keep scheduling multiple <code>Runnable</code>s with the class, the created threads never get garbage collected.</p>
  
  <pre><code>public class ThreadTest {
  
    static void runThreadWithExecutor() {
      final String name = "TestThread";
      ScheduledExecutorService ses = Executors.newSingleThreadScheduledExecutor(
          new ThreadFactory() {
            @Override
            public Thread newThread(Runnable r) {
              Thread t = new Thread(r, name);
              t.setDaemon(false);
              return t;
            }
          });
  
      ses.schedule(new Runnable() {
          @Override
          public void run() {
             System.out.println("entered " + name);
             System.out.println("exiting " + name);
          }},
        2,
        TimeUnit.SECONDS);
      }
  
    public static void main(String[] args) throws InterruptedException {
      System.out.println("entered main");
      runThreadWithExecutor();
      Thread.sleep(5000);
      System.out.println("exiting main");
    }
  }
  </code></pre>