2

I'm working on a Java fractal program. In my design, I would like to implement a particular ImageProducer class which computes pixels in a background worker thread when the startProduction(ImageConsumer) gets invoked. Once set up the producer, image will be created with Component.createImage(ImageProducer) and then shown with a call to Graphics.drawImage(Image, int, int, ImageObserver) in the paintComponent(Graphics) method of an appropriate subclass of JPanel, passing this (the JPanel) as the last parameter.

Here the question: is it safe to call setter methods on registered ImageConsumers from the worker thread? Shouldn't these calls come from the EDT for the JPanel to be painted properly?

maurizeio
  • 266
  • 2
  • 11

1 Answers1

2

In general, you must synchronize access to any data shared by two or more threads. This article discusses some of the approaches and tradeoffs. In addition, you may get some ideas for color table animation from this example. Finally, the Benojt project is a rich source of study on the topic.

Community
  • 1
  • 1
trashgod
  • 203,806
  • 29
  • 246
  • 1,045
  • @trashgod thanks for the useful links. Anyway, problem here consists that Component.createImage() (or, alternatively, Graphics.drawImage()) will surely register an ImageConsumer object for retrieving pixels but this object's class is not documented so I'm not sure it's thread-safe. – maurizeio Nov 08 '11 at 21:49
  • In general, Swing is _not_ thread-safe, as discussed [here](http://download.oracle.com/javase/7/docs/api/javax/swing/package-summary.html#threading). – trashgod Nov 08 '11 at 23:07