Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Agile forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Swing timer question.

 
Mihai Radulescu
Ranch Hand
Posts: 918
IntelliJ IDE Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ?
 
Henry Wong
author
Marshal
Pie
Posts: 20892
75
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Mihai Radulescu
Ranch Hand
Posts: 918
IntelliJ IDE Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic