C
Claudio!
Hi!
I'm new to the java.nio but I need to use (I guess) the
MappedByteBuffer. This is the case:
In a loop i produce long values to append in a file or, if some
condition apply, I need to update a previous stored value placed
somewhere in the file (random access). I know the exact position of the
value to update as the records in the file are fixed-length (i.e. 8
byte, 1 long).
At the beginning I used RandomAccessFile to update the values, but was
terribly slow. Now I'm using the MappedByteBuffer that seems to work
well. Inside a loop I call a method that contains this code:
1. FileChannel ch = file.getChannel();
2. MappedByteBuffer mbb = ch.map(MapMode.READ_WRITE, recno * 8, 8);
4. if (present) mbb.putLong(mbb.getLong(0) + 1); // the update
5. else mbb.putLong(1); // a new value appended to the file
The line 2. maps 8 byte of the file. The value of "recno" is such that
(1) or a already seen position of the file is accessed or (2) new 8
byte of the file are mapped (i. e. appended to the file and containing
the default long value 1). The flag "present" passed to the method
tells me which is the case.
Now the question: is there a better way to do this? Remeber that the
file grows in size as the loop go on, so it is impossible to map the
entire file before so I need (I guess) to map small parts of the file
at each loop (as i'm doing).
This method works (much) faster than using RandomAccessFile
readLong/writeLong directly.
Can I improve?
Thanks!!
I'm new to the java.nio but I need to use (I guess) the
MappedByteBuffer. This is the case:
In a loop i produce long values to append in a file or, if some
condition apply, I need to update a previous stored value placed
somewhere in the file (random access). I know the exact position of the
value to update as the records in the file are fixed-length (i.e. 8
byte, 1 long).
At the beginning I used RandomAccessFile to update the values, but was
terribly slow. Now I'm using the MappedByteBuffer that seems to work
well. Inside a loop I call a method that contains this code:
1. FileChannel ch = file.getChannel();
2. MappedByteBuffer mbb = ch.map(MapMode.READ_WRITE, recno * 8, 8);
4. if (present) mbb.putLong(mbb.getLong(0) + 1); // the update
5. else mbb.putLong(1); // a new value appended to the file
The line 2. maps 8 byte of the file. The value of "recno" is such that
(1) or a already seen position of the file is accessed or (2) new 8
byte of the file are mapped (i. e. appended to the file and containing
the default long value 1). The flag "present" passed to the method
tells me which is the case.
Now the question: is there a better way to do this? Remeber that the
file grows in size as the loop go on, so it is impossible to map the
entire file before so I need (I guess) to map small parts of the file
at each loop (as i'm doing).
This method works (much) faster than using RandomAccessFile
readLong/writeLong directly.
Can I improve?
Thanks!!