Skip to content

Commit fa079ba

Browse files
committed
Always return SliceByteBuf on slice(...) to eliminate possible leak
Motivation: When calling slice(...) on a ByteBuf the returned ByteBuf should be the slice of a ByteBuf and shares it's reference count. This is important as it is perfect legal to use buf.slice(...).release() and have both, the slice and the original ByteBuf released. At the moment this is only the case if the requested slice size is > 0. This makes the behavior inconsistent and so may lead to a memory leak. Modifications: - Never return Unpooled.EMPTY_BUFFER when calling slice(...). - Adding test case for buffer.slice(...).release() and buffer.duplicate(...).release() Result: Consistent behaviour and so no more leaks possible.
1 parent 17d1fa0 commit fa079ba

2 files changed

Lines changed: 16 additions & 4 deletions

File tree

buffer/src/main/java/io/netty/buffer/AbstractByteBuf.java

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -931,10 +931,6 @@ public ByteBuf slice() {
931931

932932
@Override
933933
public ByteBuf slice(int index, int length) {
934-
if (length == 0) {
935-
return Unpooled.EMPTY_BUFFER;
936-
}
937-
938934
return new SlicedByteBuf(this, index, length);
939935
}
940936

buffer/src/test/java/io/netty/buffer/AbstractByteBufTest.java

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2456,6 +2456,22 @@ public void testMemoryAddressAfterRelease() {
24562456
}
24572457
}
24582458

2459+
@Test
2460+
public void testSliceRelease() {
2461+
ByteBuf buf = newBuffer(8);
2462+
assertEquals(1, buf.refCnt());
2463+
assertTrue(buf.slice().release());
2464+
assertEquals(0, buf.refCnt());
2465+
}
2466+
2467+
@Test
2468+
public void testDuplicateRelease() {
2469+
ByteBuf buf = newBuffer(8);
2470+
assertEquals(1, buf.refCnt());
2471+
assertTrue(buf.duplicate().release());
2472+
assertEquals(0, buf.refCnt());
2473+
}
2474+
24592475
// Test-case trying to reproduce:
24602476
// https://github.com/netty/netty/issues/2843
24612477
@Test

0 commit comments

Comments
 (0)