dev@glassfish.java.net

potential file descriptor leak with failed SocketChannel creation(s)

From: charlie hunt <charlie.hunt_at_sun.com>
Date: Mon, 23 Apr 2007 11:16:42 -0500

There's file descriptor leak in
java.nio.SocketChannel.open(SocketAddress address) when a connection
initiation attempt fails. The work around is to explicitly call
SocketChannel.close() if the SocketChannel.open(SocketAddress address)
fails. Note, this could potentially be a big issue for failover type
configurations where connection initiation / attempts may occur
frequently along with frequent connection failures.

In the fwiw category, when using the SocketChannel.open() followed by a
SocketChannel.connect(SocketAddress address), (as opposed to the
SocketChannel.open(SocketAddress address()), the expectation in the
implementation of SocketChannel is that the programmer explicitly call
SocketChannel.close() if the connect(SocketAddress address) fails to
establish a connection.

If you are using Java NIO SocketChannel in your implementation, you
might want to take a look at how you are handling the establishing of a
connection. A JDK bug has been filed for file descriptor leak issue,
which can viewed at:
http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6548464

The work around is to not use the convenience method
SocketChannel.open(SocketAddress address). Instead change to using
SocketChannel.open() followed by a SocketChannel.connect(SocketAddress
address). Then use a try/catch block construct such as this one:

SocketAddress sa = new InetSocketAddress("bogus.com", 34567);
SocketChannel sc = sc.open();
try {
   sc.connect(sa);
} catch (IOException x) {
   try {
       sc.close();
   } finally {
       throw x;
   }
}

charlie ...
-- 
Charlie Hunt
Java Performance Engineer
630.285.7708 x47708 (Internal)
<http://java.sun.com/docs/performance/>