Wednesday, September 26, 2012

javax.swing.Timer and java.util.Timer

Java SE provide javax.swing.Timer and java.util.Timer to schedule tasks to be executed at regular time intervals. Here is a example demonstrate how to create javax.swing.Timer and java.util.Timer.

It can be notice that the actionPerformed() of javax.swing.Timer will be run on EDT(Event Dispatching Thread), such that it can set UI components directly. On the other hand, the TimerTask of java.util.Timer will be run on NON-EDT, it cannot set UI directly. Such that we have to create and invoke another Runnable object later in EDT to set UI components.

The event dispatching thread (EDT) is a background thread used in Java to process events from the Abstract Window Toolkit (AWT) graphical user interface event queue. These events are primarily update events that cause user interface components to redraw themselves, or input events from input devices such as the mouse or keyboard. The AWT uses a single-threaded painting model in which all screen updates must be performed from a single thread. The event dispatching thread is the only valid thread to update the visual state of visible user interface components. Updating visible components from other threads is the source of many common bugs in Java programs that use Swing. ~ Source: Event dispatching thread from Wikipedia.

So, if you want to schedule a task to perform something related to UI, you should use javax.swing.Timer. Otherwise, you can use java.util.Timer.