Can i call the method ImageIO.write(bufferedImage, 'jpg', new File(...))
...
I want to know if it's thread safe...
Sounds like you are trying to call ImageIO.write(...)
in multiple threads with different bufferedImage
all writing to the same File
. This is not going to be a problem in terms of the code being "thread safe". By calling from different threads using different bufferedImage
, there isn't going to be memory overwrite issues or other problems that we typically worry about with threads.
However, there are race conditions that might generate an invalid image file. In looking at the FileImageOutputStream
, if 2 threads are writing into the same RandomAccessFile
at the same time, you certainly could get sections of the file written by one thread with other sections written by the other thread resulting in a broken image.
I would recommend that each thread writes into their own temporary file and then rename the file into place:
// write to temporary file with thread-id suffix
File tempFile =
new File(destinationDirectory + fileName + Thread.currentThread().getId() + ".t");
ImageIO.write(bufferedImage, 'jpg', tempFile);
// rename into place
tempFile.rename(new File(fileName));
The File.rename(...)
method is an atomic operation. It's doesn't save you from the fact that the 2nd thread that calls rename will delete the 1st thread's output but it will save you from a corrupted image.