Skip to content

Commit 820cb85

Browse files
committed
Fix MultiBuffer.mapFromChannel() to avoid unnecessary buffers allocations
1 parent ac33057 commit 820cb85

File tree

1 file changed

+8
-5
lines changed

1 file changed

+8
-5
lines changed

src/main/java/com/maxmind/db/MultiBuffer.java

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -337,20 +337,23 @@ public static MultiBuffer mapFromChannel(FileChannel channel) throws IOException
337337
throw new IllegalArgumentException("File channel has no data");
338338
}
339339

340-
MultiBuffer buf = new MultiBuffer(size);
340+
int fullChunks = (int) (size / DEFAULT_CHUNK_SIZE);
341+
int remainder = (int) (size % DEFAULT_CHUNK_SIZE);
342+
int totalChunks = fullChunks + (remainder > 0 ? 1 : 0);
343+
344+
ByteBuffer[] buffers = new ByteBuffer[totalChunks];
341345
long remaining = size;
342346

343-
for (int i = 0; i < buf.buffers.length; i++) {
347+
for (int i = 0; i < totalChunks; i++) {
344348
long chunkPos = (long) i * DEFAULT_CHUNK_SIZE;
345349
long chunkSize = Math.min(DEFAULT_CHUNK_SIZE, remaining);
346-
ByteBuffer mapped = channel.map(
350+
buffers[i] = channel.map(
347351
FileChannel.MapMode.READ_ONLY,
348352
chunkPos,
349353
chunkSize
350354
);
351-
buf.buffers[i] = mapped;
352355
remaining -= chunkSize;
353356
}
354-
return buf;
357+
return new MultiBuffer(buffers, DEFAULT_CHUNK_SIZE);
355358
}
356359
}

0 commit comments

Comments
 (0)