Skip to content

batteries: Close the temporary Selector in NioPeerHandler.connect - #187

Open
saidalaoui-sq wants to merge 1 commit into
lightningdevkit:0.2from
saidalaoui-sq:nio-close-connect-selector
Open

saidalaoui-sq wants to merge 1 commit into
lightningdevkit:0.2from
saidalaoui-sq:nio-close-connect-selector

Conversation

@saidalaoui-sq

Copy link
Copy Markdown

NioPeerHandler.connect opens a Selector to wait for OP_CONNECT and never closes it. Each call leaks the selector's fds and native memory. The socket's fd also stays open after the channel closes, because the leaked selector still holds a key for it. On Linux this is 3 fds per call, on failed connects and on connects that the peer later drops. A peer that drops every connection, or an application that retries connect in a loop, runs the process out of fds.

This change closes the selector with try-with-resources. Closing it removes only its own key, so the later registration with the handler's main selector is unaffected.

The 0.1 and main branches have the same code, and this commit cherry-picks cleanly onto both.

`connect` opens a `Selector` to wait for `OP_CONNECT` and never closes
it. Each call leaks the selector's fds and native memory. The socket's
fd also stays open after the channel is closed, because the leaked
selector still holds a key for the channel, and the JDK releases a
channel's fd only once no selector has it registered.

On Linux this is 3 fds per call (epoll fd, eventfd and the socket), on
both failed connects and connects the peer later drops. A peer that
drops every connection, or an application that retries connects in a
loop, runs the process out of fds.

Close the selector with try-with-resources. Closing it removes only its
own key, so the later `register(this.selector, ...)` is unaffected.
@saidalaoui-sq
saidalaoui-sq marked this pull request as ready for review November 2, 2026 12:38
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant