Skip to main content

FileChannelImageInputStream.close does not close FileChannel

4 replies [Last post]
bokken
Offline
Joined: 2010-05-21

It appears that FileChannelImageInputStream.close() only sets the member variable to null rather than calling close() on the FileChannel (then setting to null). Is there a reason for that?

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
broumbroum
Offline
Joined: 2010-04-24

since [code]RandomAccessFile[/code] provides FileChannel to implement [b]multiple simultaneous reads on the source file[/b], it shouldn't close the backing channel, should it ?

bokken
Offline
Joined: 2010-05-21

While the documentation for FileChannel indicates that it is safe for use by multiple concurrent threads, how, practically speaking would that even work when backing an ImageInputStream? Setting the position of the channel and reading or writing data is not an atomic operation. I would expect many failures if one actually attempted to allow multiple concurrent users to access a FileChannel with at least one user trying to read an image.

The documentation for RandomAccessFile does not seem to specify whether it is safe for use by multiple concurrent threads.

There seems to be a bit of inconsistency with the ImageInputStream implementations provided. The Cache base implementations (FileCacheImageInputStream and MemoryCacheImageInputStream) both behave like FileChannelImageInputStream (they null out reference to backing InputStream at close). FileImageInputStream, which takes either a RandomAccessFile or a File will close the backing RandomAccessFile at close.

broumbroum
Offline
Joined: 2010-04-24

I think you are right, anyway those FileChannel-Cache-InputStream are definitely different from the basical FInputStr you mentioned.
Nevertheless, I'd make a better usage of FileChannel-ones "that don't close the underlying stream".
E.g. think you want to read past the source input stream you got from an external url of your network or wan't to get access to the file twice. it ain't necessary to re-instance twice back the RandomAccessFile, File or get the resource InputStream again.
That's reuseable and more flexible in that way.

bokken
Offline
Joined: 2010-05-21

Then simply do not call close on the ImageInputStream. Utilize mark/reset or seek(0).
Indeed, that would be the only way to read the content again without creating a new FileChannelImageInputStream instance.
The MappedByteBuffer is not tied to the FileChannel. So changing position in FileChannel will have no impact on the data returned by the FileChannelImageInputStream.

If you throw away the ImageInputStream instance and create another one, you then have to create a new MappedByteBuffer, which are certainly not free.