• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Why should I use a new Socket to interrupt serverSocket.accept() ?

 
Leon Omk
Ranch Hand
Posts: 75
Chrome Eclipse IDE Java
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


I want to shutdown server elegantly. In the code, serverSocket.accept() will be listening at the endpoint forever.

Approach 1, servletSocket.close() will case serverSocket.accept() to throw exception. Ugly, since my isGoingToShutdown flag is completely useless.

Approach 2, use "new Socket(serverSocket.getInetAddress(), serverSocket.getLocalPort()).close();" to interrupt serverSocket.accept(). Works. But why, why it works, and why should I do it in this way?
 
Rob Spoor
Sheriff
Pie
Posts: 20372
44
Chrome Eclipse IDE Java Windows
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It's just how the accept() method works. It blocks until a connection is made. If that's not good for you you should check out NIO and java.nio.channels.Selector. This will poll until there is actually activity; a connection request, data, etc. This polling can have a timeout so you won't have to wait indefinitely.
 
Leon Omk
Ranch Hand
Posts: 75
Chrome Eclipse IDE Java
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm curious about interrupting accept(). If accept() is invoked, a ServerSocket is listening at the endpoint(local server address+port).

If we close this ServerSocket directly, accept() would be interrupted and an exception would be thrown, saying "socket closed".

But if we create a new socket(not serverSocket) on the same endpoint, then close it. The serverSocket.accept() will stop silently without any exception thrown! Why is there no exception?
 
Rob Spoor
Sheriff
Pie
Posts: 20372
44
Chrome Eclipse IDE Java Windows
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The new socket connection will cause accept() to not wait any longer, and return the other side of the connection. Since you abort the loop immediately and the server doesn't do anything with the socket there is no code that can throw an exception. Only if you call any methods on the closed socket will an exception be thrown.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic