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?
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With