Difference between TimerTask and Executors.newScheduledThreadPool(1)

Basanth Roy picture Basanth Roy · May 24, 2011 · Viewed 9.8k times · Source

I need to schedule some work to be done in the future. I can do it in 2 ways:

  1. Create a TimerTask and execute timer.schedule(...);

  2. Use Executors.newScheduledThreadPool(1):

    ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
    ScheduledFuture <?> scheduleHandle = scheduler.schedule(pushExternalRunnable,  
            runScheduleDate.getTime() - now.getTime(), TimeUnit.MILLISECONDS);
    

What is the difference between these 2 ways of scheduling the work in the future?

Answer

dlev picture dlev · May 24, 2011

The biggest difference is that the Timer will schedule all of its tasks on a single background thread. The ExecutorService, on the other hand, will create new threads (if necessary) to run the tasks (up to the size of the pool you specify, at which point tasks will be queued.)