Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

shutdown TCP thread server

I coded a little TCP thread Server, which creates a new thread for every server.accept(). Nearly everything works great, but I have problems to kill all threads per interrupt. (I use a ServiceExecutor to manage the threads. Therefore I use the shutdownNow method to reach the interrupt-methods) The Worker-instances use a BufferedReader and it's readline-method to receive and compute the input. AFAIK the readline blocks and would not react on an interrupt, but how to stop it?

while(!isInterrupted()){

   try {
          clientSocket = this.serverSocket.accept();
        } catch(IOException e){
            break;
        }

        this.threadPool.execute(new ThreadWorker(clientSocket));
    }

    threadPool.shutdownNow();

    try{
        serverSocket.close();
    }catch(IOException e){
        //todo
    }

I tried to close the ServerSocket to kill the Input/Output Streams, but it didn't work as expected.

like image 721
NaN Avatar asked May 29 '26 09:05

NaN


1 Answers

A couple alternatives:

1) If you are closing the whole app, and there is nothing of importance to explicitly close, call System.Exit(0). HEALTH WARNING - doing this causes some developers to have apoplectic fits and post endlessly about 'cleaning up gracefully'.

2) Keep a thread-safe list of all client sockets in the accept() thread. Pass a reference to this list as part of your client context that is passed to the client<>server threads. Add new connections to the list in the accept() thread. When a client thread detects a disconnect, remove its entry from the list. When you want to close all clients, iterate the list and close the client sockets - this will cause the readline method to return early, with an error, in the client threads.

like image 61
Martin James Avatar answered May 31 '26 23:05

Martin James



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!