diff --git a/buffer/src/main/java/io/netty/buffer/PoolThreadCache.java b/buffer/src/main/java/io/netty/buffer/PoolThreadCache.java index 4eb0daf346..755f1573ed 100644 --- a/buffer/src/main/java/io/netty/buffer/PoolThreadCache.java +++ b/buffer/src/main/java/io/netty/buffer/PoolThreadCache.java @@ -337,6 +337,9 @@ final class PoolThreadCache { /** * Cache of {@link PoolChunk} and handles which can be used to allocate a buffer without locking at all. + * + * The {@link MemoryRegionCache} uses a LIFO implementation as this way it is more likely that the + * cached memory is still in the loaded cache-line and so no new read must happen (compared to FIFO). */ private abstract static class MemoryRegionCache { private final Entry[] entries; @@ -396,7 +399,8 @@ final class PoolThreadCache { * Allocate something out of the cache if possible and remove the entry from the cache. */ public boolean allocate(PooledByteBuf buf, int reqCapacity) { - Entry entry = entries[head]; + int index = prevIdx(tail); + Entry entry = entries[index]; if (entry.chunk == null) { return false; } @@ -408,7 +412,7 @@ final class PoolThreadCache { initBuf(entry.chunk, entry.handle, buf, reqCapacity); // only null out the chunk as we only use the chunk to check if the buffer is full or not. entry.chunk = null; - head = nextIdx(head); + tail = index; return true; } @@ -481,6 +485,11 @@ final class PoolThreadCache { return index + 1 & entries.length - 1; } + private int prevIdx(int index) { + // use bitwise operation as this is faster as using modulo. + return index - 1 & entries.length - 1; + } + private static final class Entry { PoolChunk chunk; long handle;