Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Thread Issues when Using a Timer

 
Kevin Simonson
Ranch Hand
Posts: 137
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Let's say I have a class that extends {JPanel} that tracks the progress of a vehicle. It has stored a velocity for that vehicle, and I use {javax.swing.Timer} to redraw the display each 100 milliseconds, say, with the vehicle having moved as far across the display as the velocity would have it move. But I also want to implement {MouseListener} so that I can increase or decrease that velocity with the click of my mouse. Do I need to synchronize access to this velocity just in case the timer goes off at the same time the user is clicking on the mouse, in order to prevent two threads from accessing the velocity at the same time and potentially corrupting the data? If so, what can I synchronize on? Should I just forget about using {javax.swing.Timer} and do the whole thing with two threads, one that handles the mouse clicks and one that periodically updates the vehicle's position?

Kevin S
 
Kevin Simonson
Ranch Hand
Posts: 137
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Kevin Simonson wrote:Let's say I have a class that extends {JPanel} that tracks the progress of a vehicle. It has stored a velocity for that vehicle, and I use {javax.swing.Timer} to redraw the display each 100 milliseconds, say, with the vehicle having moved as far across the display as the velocity would have it move. But I also want to implement {MouseListener} so that I can increase or decrease that velocity with the click of my mouse. Do I need to synchronize access to this velocity just in case the timer goes off at the same time the user is clicking on the mouse, in order to prevent two threads from accessing the velocity at the same time and potentially corrupting the data? If so, what can I synchronize on? Should I just forget about using {javax.swing.Timer} and do the whole thing with two threads, one that handles the mouse clicks and one that periodically updates the vehicle's position?

Here's an example:

So my question is, does the fact that {mousePressed()} and {actionPerformed()} both have
unsynchronized access to {velocity} raise the risk of corrupting the value of that variable? And if
so, how would I synchronize that access?

Kevin S
 
Henry Wong
author
Marshal
Pie
Posts: 21510
84
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

The javax.swing.Timer callbacks, and the swing event callbacks, all use the event-dispatching-thread. In effect, what you are describing is single threaded.

Henry
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic