diff --git a/buffer/src/main/java/io/netty/buffer/PoolArena.java b/buffer/src/main/java/io/netty/buffer/PoolArena.java index 5f7998e662..6a5b6b972d 100644 --- a/buffer/src/main/java/io/netty/buffer/PoolArena.java +++ b/buffer/src/main/java/io/netty/buffer/PoolArena.java @@ -187,15 +187,18 @@ abstract class PoolArena { buf.initUnpooled(newUnpooledChunk(reqCapacity), reqCapacity); } - void free(PoolChunk chunk, long handle, int normCapacity) { + void free(PoolChunk chunk, long handle, int normCapacity, boolean sameThreads) { if (chunk.unpooled) { destroyChunk(chunk); } else { - PoolThreadCache cache = parent.threadCache.get(); - if (cache.add(this, chunk, handle, normCapacity)) { - // cached so not free it. - return; + if (sameThreads) { + PoolThreadCache cache = parent.threadCache.get(); + if (cache.add(this, chunk, handle, normCapacity)) { + // cached so not free it. + return; + } } + synchronized (this) { chunk.parent.free(chunk, handle); } @@ -295,7 +298,7 @@ abstract class PoolArena { buf.setIndex(readerIndex, writerIndex); if (freeOldMemory) { - free(oldChunk, oldHandle, oldMaxLength); + free(oldChunk, oldHandle, oldMaxLength, buf.initThread == Thread.currentThread()); } } diff --git a/buffer/src/main/java/io/netty/buffer/PooledByteBuf.java b/buffer/src/main/java/io/netty/buffer/PooledByteBuf.java index 556dbd3713..822e6d0fb3 100644 --- a/buffer/src/main/java/io/netty/buffer/PooledByteBuf.java +++ b/buffer/src/main/java/io/netty/buffer/PooledByteBuf.java @@ -31,7 +31,7 @@ abstract class PooledByteBuf extends AbstractReferenceCountedByteBuf { protected int offset; protected int length; int maxLength; - + Thread initThread; private ByteBuffer tmpNioBuf; protected PooledByteBuf(Recycler.Handle recyclerHandle, int maxCapacity) { @@ -51,6 +51,7 @@ abstract class PooledByteBuf extends AbstractReferenceCountedByteBuf { this.maxLength = maxLength; setIndex(0, 0); tmpNioBuf = null; + initThread = Thread.currentThread(); } void initUnpooled(PoolChunk chunk, int length) { @@ -63,6 +64,7 @@ abstract class PooledByteBuf extends AbstractReferenceCountedByteBuf { this.length = maxLength = length; setIndex(0, 0); tmpNioBuf = null; + initThread = Thread.currentThread(); } @Override @@ -140,7 +142,9 @@ abstract class PooledByteBuf extends AbstractReferenceCountedByteBuf { final long handle = this.handle; this.handle = -1; memory = null; - chunk.arena.free(chunk, handle, maxLength); + boolean sameThread = initThread == Thread.currentThread(); + initThread = null; + chunk.arena.free(chunk, handle, maxLength, sameThread); recycle(); } }