Forgetting to Close a ServerSocket
If my program does not execute a ServerSocket.close()
and/or Socket.close()
before it terminates, the next time I start the program, it will always throw an IOException
when attempting to start listening on a port.
This usually happens not because I forget to put a close()
at the end of the pr开发者_Go百科ogram, rather when I force close the program and would never have a chance to execute close()
. It seems like I have to log-out and log-in on my Linux machine for it to get rid of the "occupied socket". I was wondering if anyone know a way I could clear up any unclosed sockets in case the server is forcefully ended from Terminal or any other method?
I already tried disabling and enabling my network connections, still no luck.
Contrary to your believe, you are not terminating your program. If it yould have been, the socket would have been freed, and I don't believe you have found a bug in the linux kernel here :).
It might be possible that your main thread has terminated, but your application still has non-daemon threads running that will keep your JVM alive.
After creating your threads you have to call myThread.setDaemon(true).
Are you calling [setReuseAddress()][1]
on the ServerSocket before binding it? If not, then try that.
Use the "netstat -a" command to check the status of that port. I suspect it will be in CLOSE-WAIT. This is a case of TCP working as designed and will show up in any language and OS. Eventually the kernel will timeout waiting for your program to close the socket and clear it out. You can reduce this timeout, but the best solution is to make sure your programs shuts down cleanly.
Since your concern is what will happen in case of an unexpected stop of JVM, what you need in my opinion, are shutdown hooks. Take a look at the following link: http://www.devx.com/getHelpOn/10MinuteSolution/20459/1954
What's your "program"? Does it own the process or it is just a some module to plug into a container. Terminating a process closes any sockets associated with the said process, so no need to explicit close() is needed, or not at least to prevent java.net.BindException.
Are you sure the program actually terminates its execution, that should your prime concern.
sudo /sbin/service network restart
/etc/init.d/networking restart
精彩评论