Subpages: 1. JComponent properties, size, and positioning
2. Event handling and dispatching
3. Multithreading
4. Timers
5. AppContext service
6. Inside Timers & the TimerQueue
7. JavaBeans architecture
8. Fonts, Colors, Graphics and text
9. Using the Graphics clipping area
10. Graphics debugging
11. Painting and validation
12. Focus Management
13. Keyboard input, KeyStrokes, and Actions
14. SwingUtilities
2.6 Inside Timers & the TimerQueue
class javax.swing.TimerQueue [package private]
A Timer is an object containing a small Runnable capable of dispatching ActionEvents to a list of ActionListeners (stored in an EventListenerList). Each Timer instance is managed by the shared TimerQueue instance (registered with AppContext).
A TimerQueue is a service class whose job it is to manage all Timer instances in a Java session. The TimerQueue class provides the static sharedInstance() method to retreive the TimerQueue service from AppContext. Whenever a new Timer is created and started it is added to the shared TimerQueue, which maintains a singly-linked list of Timers sorted by the order in which they will expire (i.e. time to fire the next event).
The TimerQueue is a daemon thread which is started immediately upon instantiation. This occurs when TimerQueue.sharedInstance() is called for the first time (i.e. when the first Timer in a Java session is started). It continusouly waits for the Timer with the nearest expiration time to expire. Once this occurs it signals that Timer to post ActionEvents to all its listeners, then assigns a new Timer as the head of the list, and finally removes the expired Timer. If the expired Timer's repeat mode is set to true it is added back into the list at the appropriate place based on its delay time.
Note: The real reason why the Timer example from section 2.4 would exit immediately if we didn't build a loop, is because the TimerQueue is a daemon thread. Daemon threads are service threads and when the Java virtual machine only has daemon threads running it will exit because it assumes that no real work is being done. Normally this behavior is desirable.
A Timer's events are always posted in a thread-safe mannar to the event dispatching thread by sending it's Runnable object to SwingUtilities.invokeLater().



RSS feed Java FAQ News