In a multithreaded server application, the main thread typically has a loop that calls accept() on a ServerSocket to handle incoming client connections. However, if a shutdown command is received, such as 'exit,' it becomes challenging to interrupt the blocking accept() method and exit the program gracefully.
To address this issue, consider the following approach:
Use the close() Method from Another Thread:
Example Code:
Main Thread:
<code class="java">while (listening) { try { Socket clientSocket = serverSocket.accept(); // Start client thread and add it to collection } catch (SocketException e) { // Shutdown has been initiated, break out of loop listening = false; } }</code>
Admin Thread:
<code class="java">// Create and connect to listening server socket Socket adminSocket = new Socket("localhost", port); // Wait for 'exit' command ... // Close the admin socket to interrupt the main thread adminSocket.close();</code>
By following this approach, the accept() method can be interrupted by a SocketException thrown when the ServerSocket is closed from another thread, enabling the program to exit gracefully in response to shutdown commands.
The above is the detailed content of How to Gracefully Terminate a Blocking `ServerSocket.accept()` Loop in a Multithreaded Server?. For more information, please follow other related articles on the PHP Chinese website!