2

What are the differences between, or respective limitations of, java's Timer facility and ScheduledThreadPoolExecutor service?

I know that Timer runs in single thread, but are there any other limitations apart from that?

Mathias Müller
  • 22,203
  • 13
  • 58
  • 75
aknon
  • 1,408
  • 3
  • 18
  • 29
  • 3
    The real question is; why use Timer at all when you can use ScheduledExecutorService? – Peter Lawrey Dec 30 '13 at 09:51
  • Well I am already using Timer tasks liberally, but want to shift to Scheduled Executor. Would really like to browse through all the use-cases considering limitations and benefits. – aknon Dec 30 '13 at 09:53
  • Isn't the question is why to use Timer less ? – aknon Dec 30 '13 at 10:32
  • What is the advantage of using Timer at all? – Peter Lawrey Dec 30 '13 at 12:20
  • @PeterLawrey e.g. because `ScheduledExecutorService` doesn't provide a replacement for the `Timer#schedule(TimerTask, long, long)` method. See https://stackoverflow.com/a/71794510/3882565. – stonar96 Apr 08 '22 at 09:28

1 Answers1

1

Being single threaded is the main limitation of Timer:

  • an overrun task can disrupt schedule of other tasks
  • timer is not fair with tasks, for example:

    Timer timer = new Timer();
    timer.schedule(new TimerTask() {
        @Override
        public void run() {
            System.out.println("Task#1: " + System.currentTimeMillis());
        }
    }, 1000, 1);
    timer.schedule(new TimerTask() {
        @Override
        public void run() {
            System.out.println("Task#2: " + System.currentTimeMillis());
        }
    }, 1200, 1);
    

would demonstrate that task#2 doesn't even get a shot at CPU time.

ScheduledExecutorService gives you the right level of control over level of concurrency of your tasks.

  • 1
    Task#2 does get a shot at CPU time. Below is the output at my CPU. Task#1: 1400576849729 Task#1: 1400576849730 Task#1: 1400576849731 Task#1: 1400576849732 Task#1: 1400576849733 Task#1: 1400576849734 Task#1: 1400576849735 Task#2: 1400576849735 Task#2: 1400576849736 Task#1: 1400576849736 Task#1: 1400576849737 Task#2: 1400576849737 – aknon May 20 '14 at 09:12