is this better to use javax.swing.Timer
inside of a swing application instead of using java.util.Timer
?
for example:
Timer timer = new Timer(1000, e -> label.setText(new Date().toString()));
timer.setCoalesce(true);
timer.setRepeats(true);
timer.setInitialDelay(0);
timer.start();
or
new java.util.Timer().scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
label.setText(new Date().toString());
}
}, 0, 1000);
is there any difference between this two?
javax.swing.Timer
runs onEDT
and thus should be used in conjunction withSwing
components. – HemostatTimer
also allows for the coalescing of timer events, meaning that if a "timer event" exists on the event queue, no new events will be raised until it is handled, this can prevent the saturation of the Event Queue which can lead to poor performance – Palladousjava.util.Timer
as it has certain limitations. If you really need to schedule non-UI background tasks, use aScheduledExecutorService
as it’s the more general solution harmonized with the other concurrency tools. – Absalom