private ByteBuffer getMappedByteBuffer(final long index,
final boolean forWrite) throws FileIOErrorException {
final long positionInFile = index << bitsForBufferSize;
final ByteBuffer byteBuffer;
ByteBufferNode byteBufferNode = byteBufferCacheMap.get(index);
if (byteBufferNode == null) {
if (positionInFile >= filePhysicalSize) {
byteBuffer = ByteBuffer.allocate(bufferSize);
for (int count = 0; count < bufferSize; count++) {
byteBuffer.put((byte) 0);
}
} else {
byteBuffer = fileChannelMap(FileChannel.MapMode.READ_WRITE,
positionInFile, bufferSize);
}
byteBufferNode = new ByteBufferNode(byteBuffer, index);
byteBufferCacheMap.put(index, byteBufferNode);
add(byteBufferNode);
if (byteBufferCacheMap.size() > maxNumberOfBuffer) {
// ASSERTX
final long indexOfLast = last.getIndex();
assert index != indexOfLast : "index=" + index + " size="
+ byteBufferCacheMap.size() + " maxNbBuffer="
+ maxNumberOfBuffer;
final ByteBufferNode removed = byteBufferCacheMap
.remove(indexOfLast);
// ASSERTX
assert removed == last;// NOPMD same instance
remove(last);
final ByteBuffer lastMappedByteBuffer = removed.getByteBuffer();
// if (!removed.close()) {
// throw new FileIOErrorException(CLOSED + removed.getIndex(),
// file, removed.getCloseTrace());
// }
unMap(lastMappedByteBuffer, indexOfLast, removed.isToBeWrote());
}
} else {
// ASSERTX
assert byteBufferNode.getIndex() == index;