leonbloy
leonbloy

Reputation: 75906

Is ImageIO.read() asynchronous?

Is this call supposed to be blocking, in the sense that it's guaranteed that after its execution "all" the stream has been read?

 BufferedImage image = ImageIO.read(inputStream);

I was playing with a FilterInputStream that sits between the call ImageIO.read() argument and the "real" source (say, a FileInputStream), assuming the above, but there seems to be some race conditions - difficult to reproduce. Sometimes the stream appears only half consumed after the statement execution.

There is a second related doubt: the definition of "all" the image stream can be ambiguous, consider for example PNG image that, after the pixel data can have some extra metadata (before the IEND chunk that signals the true end of the image stream). Can I expect that ImageIO.read() will read (apart from race conditions) all the image, or can it happen that the method only consumes what it need to get the pixels values?

Upvotes: 3

Views: 1532

Answers (1)

Stephen C
Stephen C

Reputation: 718788

Well, the ImageIO API does not say anything about this. It does explicitly guarantee that the image loading process will be completed. However, since there is nothing in the API of the BufferedImage class that deals with asynchronous loading (like some isLoaded() method), it is reasonable to assume that if there is asynchronous loading going on behind the scenes, it should be transparent. (And if not, that's a bug in the implementation!)

Anyway, the way to address your suspicions is to look at the source code of the image reader. If it is designed to do asynchronous loading, it will be obvious.

(I suspect that the problem is elsewhere. Maybe your filter stream or the stream it is filtering are not thread-safe and you've got multiple application threads trying to use it / them?)

Can I expect that ImageIO.read() will read (apart from race conditions) all the image, or can it happen that the method only consumes what it need to get the pixels values?

I don't think you can assume that ImageIO.read() will read the entire stream. It is not part of the spec, and (in general) it is inefficient to read more than is necessary to populate the BufferedImage.

Upvotes: 3

Related Questions