Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - IntBuffer wrapping

Tags:

java

I am reading a integer file using :

int len = (int)(new File(file).length());
FileInputStream fis = new FileInputStream(file);
byte buf[] = new byte[len];
fis.read(buf);
IntBuffer up = ByteBuffer.wrap(buf).order(ByteOrder.LITTLE_ENDIAN).asIntBuffer();

But, it creates two copies of file in memory, 1) Byte Array copy 2) IntBuffer copy.

Is it possible to use the code in such a way thus it will create only one copy in memory?

like image 738
alessandro Avatar asked Jul 11 '12 18:07

alessandro


2 Answers

The javadocs and the implementation from Oracle that I've looked at indicate that what you are saying is not true. The javadocs say that:

public static ByteBuffer wrap(byte[] array)

Wraps a byte array into a buffer.

The new buffer will be backed by the given byte array; that is, modifications to the buffer will cause the array to be modified and vice versa.

The code shows that the array passed into ByteBuffer.wrap is simply assigned as the internal array of the ByteBuffer. The ByteBuffer.asIntBuffer method simply shows the creation of an IntBuffer that uses the ByteBuffer.

like image 51
Tim Bender Avatar answered Oct 22 '22 10:10

Tim Bender


I suggest you compare this with

FileChannel fc = new FileInputStream(file).getChannel();
IntBuffer ib = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size())
        .order(ByteOrder.LITTLE_ENDIAN).asIntBuffer();

This uses less than 1 KB of heap regardless of the file size.

BTW: This can be much faster than using a heap buffer because it doesn't need to assemble each int value from bytes.

like image 42
Peter Lawrey Avatar answered Oct 22 '22 11:10

Peter Lawrey