Java: a good way to stop a threaded TCP server?

I have the following structure for TCP client-server communication:

  • On the server starting the server, an acceptor thread that accepts the connection client and passes the ServerSocket to it.
  • When a client connection arrives, accept () on ServerSocket acceptor stream calls and the client sends the job processing to the worker thread (executor / thread pool) and provides a client socket to it.
  • The worker in a cycle reads data from the client socket stream, processes and sends responses.

The question is how to gracefully stop the whole system? I can stop the acceptor stream by simply closing the ServerSocket. This will block the accept () call to throw a SocketException. But how to stop the workers? They read from the stream, and this call is blocked. According to this, the threads do not throw InterruptedException and, therefore, the worker cannot interrupt ().

Looks like I need to close the working socket from another thread, right? To do this, the socket must be created by a public field or a method must be provided to the employee to close it. Would that be good? Or maybe my whole design is spoiled?

+5
source share
3 answers

. , IO, - . , , , , - , .

+3

, . shouldStop, true, . , , ..

+2

. , , .

, , , . .

  • .
  • , , .
  • (, -
    , ). , , , trasnsactions .

EOF , .

[EDIT-1]

, , , , . , , - , , Javadocs, /

, IO, , , - Thread.interrupt() ; .

public static class IOServerWorker implements Runnable{

        private Socket socket;

        public IOServerWorker(Socket socket){
            this.socket = socket;
        }

        @Override
        public void run() {
            String line = null;
            try{
                BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                while( (line = reader.readLine())!=null){
                    System.out.println(line);
                }
                reader.close();
            }catch(IOException e){
                //TODO: do cleanup here
                //TODO: log | wrap | rethrow exception
            }
        }
    }
+2

All Articles