Home > Java > javaTutorial > How to Gracefully Terminate a Blocking `ServerSocket.accept()` Loop in a Multithreaded Server?

How to Gracefully Terminate a Blocking `ServerSocket.accept()` Loop in a Multithreaded Server?

Susan Sarandon
Release: 2024-10-25 17:44:43
Original
663 people have browsed it

How to Gracefully Terminate a Blocking `ServerSocket.accept()` Loop in a Multithreaded Server?

How to Gracefully Break Out of the Blocking ServerSocket accept() Loop

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:

  1. In a separate thread (e.g., the Admin thread), create a Socket and connect it to the listening ServerSocket on a known port. This will create a fake incoming connection from the Admin thread itself.
  2. When the Admin thread receives the 'exit' command, it calls close() on its connected Socket.
  3. In the main thread, the accept() call will throw a SocketException once the ServerSocket is closed, allowing the main thread to break out of the loop and proceed with the shutdown process.

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template