Skip to content

Ensure ServerSockets are closed in ensureComplete #2263

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

xcx1r3
Copy link

@xcx1r3 xcx1r3 commented May 29, 2025

Description

Any exception occurring before both close() calls complete successfully can lead to one or both ServerSocket instances (and the system ports they hold) not being released.
The best way to fix this is to use the try-with-resources statement, which guarantees that Closeable resources are closed, even if exceptions occur.

int quorumPort;
int electionPort;

 // Use try-with-resources to find available ports and ensure sockets are closed
try (ServerSocket randomSocket1 = new ServerSocket(0);
     ServerSocket randomSocket2 = new ServerSocket(0)) {
     quorumPort = randomSocket1.getLocalPort();
     electionPort = randomSocket2.getLocalPort();
}

@zeekling
Copy link

zeekling commented Jun 2, 2025

@xcx1r3
Copy link
Author

xcx1r3 commented Jun 5, 2025

I created an issue on https://issues.apache.org/jira/browse/ZOOKEEPER-4935.
Additionally, I discovered other resource leaks, which I have also documented in the same JIRA issue.

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.

2 participants