Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Fix JRUBY-6607, JRUBY-6498

We did not have a finally block to ensure that unsuccessful
connections were properly closed. Timeout errors would cause us
to leave the partially-initialized connection dangling, and the
JVM does not clean up socket connections on GC. Adding a finally
block and success flag appears to have tidied up lingering
sockets.
  • Loading branch information...
commit 3172fee546eb81e3e7814fdc38eabaaefc2d16c5 1 parent 3273623
@headius headius authored
Showing with 10 additions and 4 deletions.
  1. +10 −4 src/org/jruby/ext/socket/RubyTCPSocket.java
View
14 src/org/jruby/ext/socket/RubyTCPSocket.java
@@ -89,10 +89,14 @@ public IRubyObject initialize(ThreadContext context, IRubyObject[] args) {
String localHost = (args.length >= 3 && !args[2].isNil()) ? args[2].convertToString().toString() : null;
int localPort = (args.length == 4 && !args[3].isNil()) ? SocketUtils.getPortFrom(context, args[3]) : 0;
+ // try to ensure the socket closes if it doesn't succeed
+ boolean success = false;
+ SocketChannel channel = null;
+
try {
// This is a bit convoluted because (1) SocketChannel.bind is only in jdk 7 and
// (2) Socket.getChannel() seems to return null in some cases
- SocketChannel channel = SocketChannel.open();
+ channel = SocketChannel.open();
Socket socket = channel.socket();
if (localHost != null) {
@@ -110,16 +114,14 @@ public IRubyObject initialize(ThreadContext context, IRubyObject[] args) {
channel.configureBlocking(true);
initSocket(runtime, new ChannelDescriptor(channel, newModeFlags(runtime, ModeFlags.RDWR)));
+ success = true;
} catch (NoRouteToHostException nrthe) {
- channel.close();
throw runtime.newErrnoEHOSTUNREACHError("SocketChannel.connect");
} catch(ConnectException e) {
- channel.close();
throw runtime.newErrnoECONNREFUSEDError();
} catch(UnknownHostException e) {
- channel.close();
throw SocketUtils.sockerr(runtime, "initialize: name or service not known");
}
@@ -136,6 +138,10 @@ public IRubyObject initialize(ThreadContext context, IRubyObject[] args) {
} catch (IllegalArgumentException iae) {
throw SocketUtils.sockerr(runtime, iae.getMessage());
+ } finally {
+ if (!success && channel != null) {
+ try {channel.close();} catch (IOException ioe) {}
+ }
}
return context.nil;
Please sign in to comment.
Something went wrong with that request. Please try again.