P
Paul J. Lucas
I'm using FileChannel.map() to read through large image files.
I have a utility function to return a ByteBuffer from a file:
public static ByteBuffer map( File file ) throws IOException {
final FileInputStream fis = new FileInputStream( file );
final FileChannel fc = fis.getChannel();
try {
return fc.map(FileChannel.MapMode.READ_ONLY, 0, file.length());
}
finally {
fis.close();
}
}
So as not to keep the ByteBuffer around indefinitely, I have an
object that uses a WeakReference to it:
public synchronized ByteBuffer getByteBuffer() throws IOException {
ByteBuffer strongRef;
if ( m_weakRef == null ||
(strongRef = (ByteBuffer)m_weakRef.get()) == null )
{
strongRef = ByteBufferUtil.map( m_imageFile );
m_weakRef = new WeakReference( strongRef );
}
return strongRef;
}
And yet my program, after reading many image files, runs out of
memory. Assuming I don't hang on to the strong references to
the ByteBuffer by mistake elsewhere, is there anything wrong
with the above code? Is this the right way to used mapped
ByteBuffers?
- Paul
I have a utility function to return a ByteBuffer from a file:
public static ByteBuffer map( File file ) throws IOException {
final FileInputStream fis = new FileInputStream( file );
final FileChannel fc = fis.getChannel();
try {
return fc.map(FileChannel.MapMode.READ_ONLY, 0, file.length());
}
finally {
fis.close();
}
}
So as not to keep the ByteBuffer around indefinitely, I have an
object that uses a WeakReference to it:
public synchronized ByteBuffer getByteBuffer() throws IOException {
ByteBuffer strongRef;
if ( m_weakRef == null ||
(strongRef = (ByteBuffer)m_weakRef.get()) == null )
{
strongRef = ByteBufferUtil.map( m_imageFile );
m_weakRef = new WeakReference( strongRef );
}
return strongRef;
}
And yet my program, after reading many image files, runs out of
memory. Assuming I don't hang on to the strong references to
the ByteBuffer by mistake elsewhere, is there anything wrong
with the above code? Is this the right way to used mapped
ByteBuffers?
- Paul