Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Diferences in this two approaches to sleep the excecution in java

Except the delay option in the constructor of the schedule method, what is the main differences in this two approaches and what of these two approaches is the best in performance or thread-safety execution??

Timer temporizer = new Timer();
TimerTask task = new TimerTask(){
    @Override
    public void run() {
        // iterate something
    }
};
temporizer.schedule (task,delay,interval);

or a simple

while (true){
    // iterate something
    try { 
        Thread.sleep(interval); 
    } catch (InterruptedException ex) {...}
}

Thanks in advance :)

like image 599
HCarrasko Avatar asked Jan 25 '26 00:01

HCarrasko


1 Answers

The main benefit of the Timer approach vs. your sleep-based implementation is that you can cancel it. By doing a while(true) in the sleep version, you really don't have a way to cancel it cleanly.

I would also argue, and this is subjective, that the Timer approach more clearly expresses what you are trying to do. To clarify though, these are both perfectly understandable and anybody else looking at this code would probably "get it".

Another benefit to the Timer approach is that you can encapsulate your iteration logic in the TimerTask and keep it separated from the actual timing and scheduling. This would make it easier to test. Even more so if you put it in its own class instead of defining it the way you are there.

like image 124
Todd Avatar answered Jan 26 '26 16:01

Todd



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!