Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - closing a ServerSocket without Exceptions?

For years I've been wondering what the correct way to close a listening ServerSocket in Java is. My implementations always work like this, they:

  1. Create a new ServerSocket(int).
  2. Start a thread that calls its accept() method in a while (true) loop.
  3. Start another thread when accept() returns (client connects) that reads from the client until it disconnects. The accept thread then continues with another accept() call.

But when I want to close the ServerSocket because my application is exiting, I've never found another way of doing so other than calling it's close() method (after I've closed all client Sockets), which causes accept() to throw a SocketException, I catch that and break from the while (true) loop in the accept thread, causing all my threads to exit.

I think this is ugly, strictly speaking there is no exception occurring, closing my ServerSocket is part of my programs normal operation.

Is there really no other way of doing this without causing an Exception to be thrown?

Thanks.

like image 497
0ne_Up Avatar asked Mar 04 '26 06:03

0ne_Up


1 Answers

I've never found another way of doing so other than calling it's close() method (after I've closed all client Sockets),

You can set a flag closed = true; and open a dummy connection to wake up the accept()ing thread which checks the flag before continuing.

which causes accept() to throw a SocketException,

A SocketClosedException which is expected behaviour here.

I catch that and break from the while (true) loop in the accept thread,

If you catch it outside the loop, you don't need to also break out of the loop. If the exception is thrown and you have set closed = true you can discard the exception.

BTW I would do

while(!serverSocket.isClosed()) {

causing all my threads to exit.

There is no particular reason you need to have this, but you can choose to do this if you want.

I think this is ugly, strictly speaking there is no exception occurring,

An exceptional condition is happening. What is not happening is an Error.

closing my ServerSocket is part of my programs normal operation.

Or you could say it is operating normally when it is running and not shutting down.

like image 124
Peter Lawrey Avatar answered Mar 06 '26 20:03

Peter Lawrey