+ Reply to Thread
Results 1 to 2 of 2

Thread: ScheduledExecutorService never get garbage collected

  1. #1
    Junior Member
    Join Date
    May 2012
    Posts
    7

    ScheduledExecutorService never get garbage collected

    I have created a thread "ThreadTest" , but after keep scheduling multiple threads , the created threads never get garbage collected.
    Here is my code sample :
    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");
      }
    }

  2. #2
    Junior Member
    Join Date
    Jan 2012
    Posts
    36
    This is due to the fact that you are not calling shutdown() on your executor service after you have scheduled your last job:
    Code:
    ses.schedule(...);
    // this stops any management threads but existing jobs will still run
    ses.shutdown();

+ Reply to Thread

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts