Aadit M Shah
Aadit M Shah

Reputation: 74204

Forgetting to close a server socket in Java

What happens when you forget to close a ServerSocket in Java? Does the JVM or the TCP/IP stack automatically close it for you?

In addition when you close a ServerSocket does it also close all the associated Socket connections it spawned via the accept method?

Upvotes: 0

Views: 1664

Answers (3)

user207421
user207421

Reputation: 310869

Does the JVM or the TCP/IP stack automatically close it for you?

The JVM may close it if it ever gets garbage-collected. The TCP/IP stack will close it when the process exits. You don't state under what conditions you expect the action to occur so it is impossible to be more specific.

when you close a ServerSocket does it also close all the associated Socket connections it spawned via the accept method?

Definitely not.

Upvotes: 0

Peter Lawrey
Peter Lawrey

Reputation: 533482

What happens when you forget to close a ServerSocket in Java?

The GC will finalise the ServerSocket closing it eventually but you can't say when this will happen (or possibly it might never happen)

Does the JVM or the TCP/IP stack automatically close it for you?

Its the JVM. The TCP/IP stack has no idea it should be closed.

In addition when you close a ServerSocket does it also close all the associated Socket connections it spawned via the accept method?

A ServerSocket is used for establishing a connection and once it has been accepted it is no different to those created on the client side. Closing the server socket has no effect on accepted connections. (It will close those which have not been accepted)

Upvotes: 1

Jim Garrison
Jim Garrison

Reputation: 86764

All the resources will get shut down and released by the OS when the JVM terminates.

Upvotes: 3

Related Questions