Thread.sleep() VS Executor.scheduleWithFixedDelay()

前端 未结 4 944
萌比男神i
萌比男神i 2020-12-30 23:52

Goal: Execute certain code every once in a while.

Question: In terms of performance, is there a significant difference between:

while(true) {
    exe         


        
4条回答
  •  天涯浪人
    2020-12-31 00:04

    There are different scenarios,

    1. The Timer creates a queue of tasks that is continually updated. When the Timer is done, it may not be garbage collected immediately. So creating more Timers only adds more objects onto the heap. Thread.sleep() only pauses the thread, so memory overhead would be extremely low
    2. Timer/TimerTask also takes into account the execution time of your task, so it will be a bit more accurate. And it deals better with multithreading issues (such as avoiding deadlocks etc.).
    3. If you thread get exception and gets killed, that is a problem. But TimerTask will take care of it. It will run irrespective of failure in previous run
    4. The advantage of TimerTask is that it expresses your intention much better (i.e. code readability), and it already has the cancel() feature implemented.

    Reference is taken from here

提交回复
热议问题