I've been reading Filthy Rich Clients lately and noticed that, although the version of Java is 6, there is no mention of the Concurrent Framework. So, they talk about java.util.Timer and javax.swing.Timer but not about the ExecutorService.
I read about the advantages of ExecutorService in the question "Java Timer vs ExecutorService" and decided to use the latter over the former. But the book talks about javax.swing.Timer and it's advantages of being specific for Swing development.
So, does this mean that, for Swing development (animating buttons etc.), javax.swing.Timer is still a better choice or is there a relevant class in the new Concurrent Framework that replaces it?
Well the Swing Timer at least runs on the EDT so you do not have to wrap everything with calls to invokeLater. It also ties nicely in with Swing as it uses Actions, ActionListeners and other Swing related classes.
I'd stick with Swing Timer for Swing related tasks and use the new concurrent package for things that does not involve updating the GUI.
Have a look at Using Timers in Swing Applications as it might contain more information to swing (sorry) the decision.
I would say that for simple swing related stuff the better choice is the javax.swing.Timer
because of the advantages mentioned here.
Note that the Swing timer's task is
performed in the event dispatch
thread. This means that the task can
safely manipulate components, but it
also means that the task should
execute quickly.
On the other side, if you need to perform non-swing related or more complex/lengthy processing operations, the ExecutorService
is very robust and is definitely the way to go.
Just a suggestion elaborating on what bruno advised, one pattern for taking advantage of the excellent Java 1.5+ concurrency utilities without breaking Swing is to have your ExecutorService
do all the heavy lifting (as bruno said) but once that is done, the ExecutorService
thread should hand off the interaction with the actual UI components to the AWT Thread in a Runnable using one of:
javax.swing.SwingUtilities.invokeAndWait(Runnable doRun)
javax.swing.SwingUtilities.invokeLater(Runnable doRun)
Those methods pass the runnable to be executed by the AWT thread.