views:

2066

answers:

4

If I open and close a socket by calling for instance

Socket s = new Socket( ... );
s.setReuseAddress(true);
in = s.getInputStream();
...
in.close(); 
s.close();

Linux states that this socket is still open or at least the file descriptor for the connection is presen. When querying the open files for this process by lsof, there is an entry for the closed connection:

COMMAND  PID   USER   FD   TYPE DEVICE     SIZE   NODE NAME
java    9268 user    5u  sock    0,4           93417 can't identify protocol

This entry remains until the program is closed. Is there any other way to finally close the socket? I'm a little worried that my java application may block to many file descriptors. Is this possible? Or does java keep these sockets to re-use them even is ReuseAdress is set?

A: 

Maybe it's a socket of some other protocol ("Can't identify protocol" eh?) used internally in the implementation to do something, which gets created on the first socket.

Have you tried repeatedly creating sockets and closing them, to see if these sockets really persist? It seems likely that this is a one-off.

Java probably uses sockets internally for lots of things - they might be Unix, Netlink (under Linux) or some other type of socket.

MarkR
+3  A: 

If those sockets are all in the TIME_WAIT state, this is normal, at least for a little while. Check that with netstat; it is common for sockets to hang around for a few minutes to ensure that straggling data from the socket is successfully thrown away before reusing the port for a new socket.

Richard Campbell
Agreed -- this is the first thing to check. And after a few minutes, the sockets should go away, before your program necessarily terminates.
Neil Coffey
The author states the entries remain until the program closes, though I guess he doesn't specify if that's more than a few minutes.
Ry4an
Yeah, I saw the "program closes" bit, but wasn't sure.
Richard Campbell
A: 

Create a small bash script to monitor opened sockets for a certain app or pid, and let it run while testing your java app.

I doubt anyway that there are any kind of leaks in this thing as sockets are very used in linux/unix world and this kind of problem would bubble up very quicky

Quamis
+1  A: 

You may also want to check /proc/<pid>/fd, the directory will contain all of your currently opened file descriptors. If a file disappears after you closed the socket you will not run into any problems (at least not with your file descriptors :).

Bombe