What is the difference between the java.util.Timer and javax.swing.Timer classes?

Asked

Viewed 333 times

1

Java has the homonymous classes javax.swing.Timer and java.util.Timer. I understand that the first may have some kind of specific functioning for the swing API, and I thought that it extended the second, but this does not occur, as documentation.

What is the difference between the two classes? The fact that I use util.Timer in a graphical application with or the swing.Timer in a code that does not use the graphical API may cause some compatibility problem?

1 answer

1


The big difference is that the javax.swing.Timer executes his task in the Event Thread (EDT = Event Dispatch Thread). Therefore it is indicated to manipulate GUI components.

The java.util.Timer uses a Thread normal to execute their tasks. Each Timer instance creates its own Thread.

The Swing Timer documentation explains this, only not very easy to understand (in my opinion):

Although all Timers perform their Waiting using a single, Shared thread (created by the first Timer Object that executes), the action Event handlers for Timers execute on Another thread -- the Event-dispatching thread. This Means that the action handlers for Timers can Safely perform Operations on Swing Components. However, it also Means that the handlers must execute quickly to Keep the GUI Responsive.

In v 1.3, Another Timer class was Added to the Java Platform: java.util.Timer. Both it and javax.swing.Timer provide the same basic Functionality, but java.util.Timer is more general and has more Features. The javax.swing.Timer has two Features that can make it a little easier to use with Guis. First, its Event Handling Metaphor is familiar to GUI programmers and can make dealing with the Event-dispatching thread a bit Simpler. Second, its Automatic thread sharing Means that you don’t have to take special Steps to avoid spawning Too Many threads. Instead, your timer uses the same thread used to make Cursors Blink, tool tips appear, and so on.

Problems:

1) use java.util.Timer with Swing: the methods of the Swing components must be called in the Thread EDT, which does not occur (automatically) with this Timer.

2) use javax.swing.Timer with non-swing elements: it will be a problem if operations are delayed as they will eventually block the graphical interface.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.