semisimpleton
semisimpleton

Reputation: 121

Can Sockets in be closed in any other way except for socket.close()?

I just want to clear a doubt that I've been harboring for quite some time now: Is it possible for sockets in Java to be closed even if the .close() method hasn't been called in the code?

Upvotes: 1

Views: 80

Answers (2)

WalterM
WalterM

Reputation: 2706

This code below is in java.net.AbstractPlainSocketImpl

/**
 * Cleans up if the user forgets to close it.
 */
protected void finalize() throws IOException {
    close();
}

finalize() gets called when the garbage collector is run. So if you lose all references to your Socket, it will be closed. You shouldn't do this though, as it's bad practice - you never know when the garbage collector will run, so the socket could stay open for awhile. I don't really know if this counts as it does call close() underneath. Closing input, and output streams are different that the socket. I don't think they really count.

Upvotes: 1

user207421
user207421

Reputation: 310913

Yes. Closing either the input or the output stream of the socket closes the other stream and the socket.

Upvotes: 1

Related Questions