5

In Java, is there a difference between setting a socket with Socket.setSoLinger(true, 0) and not calling setSoLinger at all? Is there a difference in how the socket is closed?

I have looked through the Java sources, and I don't see anything special around socket closes with regards to soLinger. This leads me to believe this is an OS specific behavior. In my case I am working on Linux.

mmorrisson
  • 541
  • 8
  • 19
  • See http://stackoverflow.com/questions/922951/java-network-server-and-time-wait & http://stackoverflow.com/questions/1490196/tcp-connection-in-time-wait-wont-allow-reconnect-java – Zaki Mar 11 '12 at 21:37

2 Answers2

3

When a timeout is specified via setSoLinger(), close() blocks until the closing hand-shake is completed, or until the specified amount of time passes.

However, close() provides no indication that the closing handshake failed to complete, even if the time limit set by setSoLinger() expires before the closing sequence completes.

In other words, setSoLinger() does not provide any additional assurance to the application in current implementations.

Here's the source of info.

Zaki
  • 6,997
  • 6
  • 37
  • 53
3

Socket.setSoLinger(true, 0) is actually the default, so there is no difference whatsoever. However see also Zaki's answer for why even a non-zero value is futile anyway in Java. Socket.close() ignores the errno that is generated if the timeout expires. I pointed out this problem about ten years ago and got the reply that it couldn't be changed for backward compatibility reasons. I don't agree actually, but there you go. However the NIO2 stuff in Java 7 does recognize this case and throw an exception properly.

user207421
  • 305,947
  • 44
  • 307
  • 483