Brian
Brian

Reputation: 8085

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 program, 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.

Upvotes: 2

Views: 3781

Answers (7)

bestsss
bestsss

Reputation: 12056

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.

Upvotes: 0

Daniel
Daniel

Reputation: 28074

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).

Upvotes: 5

Nikola Yovchev
Nikola Yovchev

Reputation: 10216

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

Upvotes: 0

JOTN
JOTN

Reputation: 6317

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.

Upvotes: 0

Cratylus
Cratylus

Reputation: 54074

/etc/init.d/networking restart

Upvotes: -2

Steve Emmerson
Steve Emmerson

Reputation: 7832

Are you calling [setReuseAddress()][1] on the ServerSocket before binding it? If not, then try that.

Upvotes: 0

vinnyjames
vinnyjames

Reputation: 2068

sudo /sbin/service network restart

Upvotes: -2

Related Questions