How can I make a socket close immediately, bypassing the timeout period?

11,583

Solution 1

I found out that by using socket.setReuseAddress(boolean), you can tell the JVM to reuse the port even if it's in the timeout period.

Solution 2

You are probably seeing sockets in TIME_WAIT state. This is the normal state for a socket to enter on the side of the connection that does the 'active close'. TIME_WAIT exists for a very good reason and so you should be careful of simply reusing addresses.

I wrote about TIME_WAIT, why it exists and what you can do about it when writing servers here on my blog: http://www.serverframework.com/asynchronousevents/2011/01/time-wait-and-its-design-implications-for-protocols-and-scalable-servers.html

In summary, if you can, change the protocol so that your clients enter TIME_WAIT.

Solution 3

If you're running a server, then ServerSocket is the proper solution. It will manage everything better than you doing it by hand through recycling and a host of other optimizations intended for running a server with Java.

Closing the socket disconnects the Java object from the operating system, which means that it isn't taking up any resources outside of the JVM, so it really shouldn't be a problem. But if the minimal overhead from Java's garbage collection/finalization scheme is too big of a burden, then Java isn't a valid solution (since your problem isn't specific to socket programming any more). Although I have to say that an efficient garbage collector is not much worse than explicitly managing memory (and can actually perform better).

Solution 4

'I want them to be closed exactly after closed them not after wasting my time and my resources!' No you don't. You want TCP/IP to work correctly, and the TIME_WAIT state is a critically important part of that. If you're worried about the TIME_WAIT state, the quick answer is to be the one who receives the FIN rather than the one who first sends it.

Share:
11,583
Shayan
Author by

Shayan

I'm a PhD student in The University Of Tehran and I love my major.

Updated on June 23, 2022

Comments

  • Shayan
    Shayan almost 2 years

    In Java, when you close a socket, it doesn't do anything anymore, but it actually closes the TCP connection after a timeout period.

    I need to use thousands of sockets and I want them to be closed immediately after I close them, not after the timeout period, which wastes my time and my resources. What can I do?