The program I have visualizes a physics simulation (basically). Right now, it works, but can get very unresponsive, and I think I know why - too much (read:all) computation is done on the event thread.
When the 'play' button is pressed, a Swing Timer
is created that wakes up periodically and calls updateTime()
- so far so good. The problem is that updateTime()
iterates through every time-dependent object and tells it to propagate itself forwards in time by the appropriate amount (either the real time elapsed, or an arbitrary time unit each tick). These calculations, and the subsequent GUI updates, are all on the event dispatch thread.
So, I'd like to offload as much of this computation as possible, and I think SwingWorker
s are the way to go, but I'm not sure how to work them into the existing code. I can't have the existing classes extend SwingWorker
since many of them already extend other classes.
My best idea so far is to create an interface for each time-dependent object to implement. The interface would specify 2 methods, calcUpdateTime()
and drawUpdateTime()
. I would split up each of their current updateTime()
methods into the physics calculations (into calc_
) and GUI updates (into draw_
). Then I would create only one class of SwingWorker that takes a TimeDependant
object in the constructor, and its doInBackground
would call calcUpdateTime
and done
would call drawUpdateTime
. So then I can replace all occurrences of
myObj.updateTime(currentTime);
with
new MySwingWorker(myObj, currentTime).execute();
I wanted to run this idea by SO because it doesn't feel quite right, and it would like to avoid refactoring the entire project just to find out I started out with a bad idea. Also, isn't it probably a bad idea to create potentially dozens of MySwingWorker
s each tick?
Thanks for reading this far.