I have a background thread that produces pixels of an image (suppose a java.awt.image.BufferedImage
) in a top-down left-right fashion and I want the Swing gui to paint the available portion of the image at regular intervals, to show progress to the user.
As far as I undertood from many answers, BufferedImage
is not thread-safe so I'm wondering if it's possible to use a java.util.concurrent.Semaphore
to enforce synchronization and memory consistency. The background thread would call release()
on the semaphore after every pixel write operation while a javax.swing.Timer
would call drainPermits()
on the semaphore and request the returned number of pixels to be painted. I guess this scheme should work because the documentation of Semaphore
states that:
Actions in a thread prior to calling a "release" method such as
release()
happen-before actions following a successful "acquire" method such asacquire()
in another thread.
Please tell me if I am correct.