From 2aa35922b47f6c65a5f6114965d33cdd8078e197 Mon Sep 17 00:00:00 2001 From: Norman Maurer Date: Sat, 5 Apr 2014 19:27:09 +0200 Subject: [PATCH] [#2363] SelectedSelectionKeySet may hold strong reference to SelectionKey after Channel is closed Motivation: Because we not null out the array entry in the SelectionKey[] which is produced by SelectedSelectionKeySet.flip() we may end up with a few SelectionKeyreferences still hanging around here even after the Channel was closed. As these entries may be present at the end of the SelectionKey[] which is never updated for a long time as not enough SelectionKeys are ready. Modifications: Once we access the SelectionKey out of the SelectionKey[] we directly null it out. Result: Reference can be GC'ed right away once the Channel was closed. --- .../java/io/netty/channel/nio/NioEventLoop.java | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/transport/src/main/java/io/netty/channel/nio/NioEventLoop.java b/transport/src/main/java/io/netty/channel/nio/NioEventLoop.java index e68c1a7b83..617fe9a739 100644 --- a/transport/src/main/java/io/netty/channel/nio/NioEventLoop.java +++ b/transport/src/main/java/io/netty/channel/nio/NioEventLoop.java @@ -454,6 +454,9 @@ public final class NioEventLoop extends SingleThreadEventLoop { if (k == null) { break; } + // null out entry in the array to allow to have it GC'ed once the Channel close + // See https://github.com/netty/netty/issues/2363 + selectedKeys[i] = null; final Object a = k.attachment(); @@ -466,6 +469,16 @@ public final class NioEventLoop extends SingleThreadEventLoop { } if (needsToSelectAgain) { + // null out entrys in the array to allow to have it GC'ed once the Channel close + // See https://github.com/netty/netty/issues/2363 + for (;;) { + if (selectedKeys[i] == null) { + break; + } + selectedKeys[i] = null; + i++; + } + selectAgain(); // Need to flip the optimized selectedKeys to get the right reference to the array // and reset the index to -1 which will then set to 0 on the for loop