MappedByteBuffer

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!!
 
T

Thomas Hawtin

Claudio! said:
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).

I'm not expert, but: MappedByteBuffer is a bit nasty. For instance,
there is no unmap (yet). I suggest either extending the file in large
chunks (this may reduce fragmentation as a side-effect) or using plain
old FileChannel.write(ByteBuffer) without mapping.

Tom Hawtin
 
T

Tim Ward

Thomas Hawtin said:
I'm not expert, but: MappedByteBuffer is a bit nasty.

I found it completely unusable, as it keeps the file locked until the next
garbage collection time, which is unpredictable and could be days after
someone else really wanted to use that file.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,776
Messages
2,569,603
Members
45,188
Latest member
Crypto TaxSoftware

Latest Threads

Top