Sam Goldberg
Sam Goldberg

Reputation: 6801

Java NIO socket application: reuse SocketChannel or throw away on lost connection?

I am working on a middleware application which creates and maintains TCP/IP connections to several servers. If the application detects that a connection has been lost, it will try to reconnect on a timer until the connection is reestablished.

The application is using java.nio.SocketChannel objects in non-blocking mode, with Selector/SelectionKey to handle the socket events.

Once a connection is lost, is it better to throw away the current SocketChannel object, and create a new one to reconnect (also get a new SelectionKey), or to reuse the same SocketChannel and SelectionKey (which I guess is invalid until connection is established again)?

Upvotes: 0

Views: 2647

Answers (1)

Mike Q
Mike Q

Reputation: 23229

You must throw it away. When a connection is lost you must close the SocketChannel on your end to clean up the connection correctly. If you want to try to reconnect then just do exactly what you did the first time (createSocket, make non blocking, init connection etc).

Upvotes: 2

Related Questions