Java Timer vs ExecutorService?

前端 未结 6 1351
孤独总比滥情好
孤独总比滥情好 2020-11-21 23:51

I have code where I schedule a task using java.util.Timer. I was looking around and saw ExecutorService can do the same. So this question here, hav

6条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-22 00:43

    From Oracle documentation page on ScheduledThreadPoolExecutor

    A ThreadPoolExecutor that can additionally schedule commands to run after a given delay, or to execute periodically. This class is preferable to Timer when multiple worker threads are needed, or when the additional flexibility or capabilities of ThreadPoolExecutor (which this class extends) are required.

    ExecutorService/ThreadPoolExecutor or ScheduledThreadPoolExecutor is obvious choice when you have multiple worker threads.

    Pros of ExecutorService over Timer

    1. Timer can't take advantage of available CPU cores unlike ExecutorService especially with multiple tasks using flavours of ExecutorService like ForkJoinPool
    2. ExecutorService provides collaborative API if you need coordination between multiple tasks. Assume that you have to submit N number of worker tasks and wait for completion of all of them. You can easily achieve it with invokeAll API. If you want to achieve the same with multiple Timer tasks, it would be not simple.
    3. ThreadPoolExecutor provides better API for management of Thread life cycle.

      Thread pools address two different problems: they usually provide improved performance when executing large numbers of asynchronous tasks, due to reduced per-task invocation overhead, and they provide a means of bounding and managing the resources, including threads, consumed when executing a collection of tasks. Each ThreadPoolExecutor also maintains some basic statistics, such as the number of completed tasks

      Few advantages:

      a. You can create/manage/control life cycle of Threads & optimize thread creation cost overheads

      b. You can control processing of tasks ( Work Stealing, ForkJoinPool, invokeAll) etc.

      c. You can monitor the progress and health of threads

      d. Provides better exception handling mechanism

提交回复
热议问题