File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Threads and Synchronization and the fly likes Swing timer question. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "Swing timer question." Watch "Swing timer question." New topic
Author

Swing timer question.

Mihai Radulescu
Ranch Hand

Joined: Sep 18, 2003
Posts: 916

Hallo

I just read the "Taming threads" from Allen Holub and on the chapter "Timer, alarms, and thread safety" I have a question about the swing timers action listern.
As long as I understand if you pass an (java.awt)ActionListenr to a (javax.swing) Timer, the time queue thread handle this by using the (javax.swing) SwingUtilities.invokeLater - in the runnable paramter is the actionPerformed method from your ActionListener - so the code runs save on the swing event-processing thread, no need for synchronozation stuff.
To make it more easy you can desctibe the situation like :

ActionListener -> SwingUtilities.invokeLater -> run(runnable target) -> actionPerformed.

Until here all is logic.But on the example he synchronizes the ActionListener with the outer-class object.



Why this extra "synchronized" , the actionPerformed() method run anyway on the swing dispatcher thread ?


SCJP, SCJD, SCWCD, OCPJBCD
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18760
    
  40

Why this extra "synchronized" , the actionPerformed() method run anyway on the swing dispatcher thread ?


The actionPerformed() method runs in the event dispatching thread. Hence, there is no need to synchronized it with other methods that also run on the event dispatching thread.

However, I am willing to bet that there are other methods that may not run on the event dispatching threads. Methods that are part of the outer class, that access the elasped_time and done variables.

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Mihai Radulescu
Ranch Hand

Joined: Sep 18, 2003
Posts: 916

Yeep, you' right, the ActionListener actionPerformed method access a instance member field (the done), and a reason for the syncronization is to make the atomic the block where the memeber field is used - see the code :


I don't see other reasons.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
 
subject: Swing timer question.