Reputation: 1316
Just a quick one - I'm in the process of writing a Sega Master System emulator. The design thus far is that the GUI (JFrame subclass etc.) runs in the Event Dispatch Thread, via an EventQueue.invokeLater() call, and all the emulator functions run in a separate thread. From what I understand this is supposed to be good practice, as the EDT is supposed to initialise and update the GUI, with Swing not being thread-safe.
This leads me to a small question - the console runs in the separate thread (Z80, VDP, etc.) and the VDP (when I've finished it) will update a BufferedImage. As long as I mark this BufferedImage as 'synchronized', is it safe to then access it from the EDT (the GUI's paint method in particular)? I ask this as otherwise I will have to put a lot of VDP logic into the paint method itself, and I'd rather not do this, as it will slow down the GUI overall.
Simple question I know, but I'm still getting used to pushing Java2D for decent speed animation. It is worth mentioning that right after the repaint() method is called in the logic thread, the logic thread will sleep until woken for the next frame pass, so I'm guessing there won't be a performance hit from this design - am I right?
Many thanks, Phil Potter
UPDATE I should have used better language - the VDP will be accessing the BufferedImage through a synchronized setter method and the EDT will be accessing it through a synchronized getter method.
Upvotes: 3
Views: 375
Reputation: 4593
I don’t think you need to make the setter and getter synchronized since they should only be accessed from EDT. So lets take a step back. You said that the getter will be accessed from EDT -- so we are thread safe here. Now with the setter method will be run on the VDP -- to handle this case we want to call invokeLater ( see example). Take look here for more info.
Runnable updateAComponent = new Runnable() {
public void run() {
//this will run in the EDT
component.doSomething();
}
};
//this will run in the VDP
SwingUtilities.invokeLater(updateAComponent);
Upvotes: 2