Java Timer vs ExecutorService?

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

    My reason for sometimes preferring Timer over Executors.newSingleThreadScheduledExecutor() is that I get much cleaner code when I need the timer to execute on daemon threads.

    compare

    private final ThreadFactory threadFactory = new ThreadFactory() {
        public Thread newThread(Runnable r) {
            Thread t = new Thread(r);
            t.setDaemon(true);
            return t;
        }
    };
    private final ScheduledExecutorService timer = Executors.newSingleThreadScheduledExecutor(threadFactory); 
    

    with

    private final Timer timer = new Timer(true);
    

    I do this when I don't need the robustness of an executorservice.

提交回复
热议问题