Java Timer vs ExecutorService?

前端 未结 6 1342
孤独总比滥情好
孤独总比滥情好 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:41

    If it's available to you, then it's difficult to think of a reason not to use the Java 5 executor framework. Calling:

    ScheduledExecutorService ex = Executors.newSingleThreadScheduledExecutor();
    

    will give you a ScheduledExecutorService with similar functionality to Timer (i.e. it will be single-threaded) but whose access may be slightly more scalable (under the hood, it uses concurrent structures rather than complete synchronization as with the Timer class). Using a ScheduledExecutorService also gives you advantages such as:

    • You can customize it if need be (see the newScheduledThreadPoolExecutor() or the ScheduledThreadPoolExecutor class)
    • The 'one off' executions can return results

    About the only reasons for sticking to Timer I can think of are:

    • It is available pre Java 5
    • A similar class is provided in J2ME, which could make porting your application easier (but it wouldn't be terribly difficult to add a common layer of abstraction in this case)

提交回复
热议问题