3

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.

NaN
  • 3,501
  • 8
  • 44
  • 77
  • 3
    Ideally, don't call methods that block indefinitely. – David Schwartz Oct 29 '12 at 09:35
  • See also http://stackoverflow.com/questions/671049/how-do-you-kill-a-thread-in-java?rq=1 and http://stackoverflow.com/questions/1948317/forceful-termination-of-a-thread-stuck-on-an-api-call-of-some-method?rq=1 – DNA Oct 29 '12 at 09:53
  • In `C` I'd say just send a signal. – alk Oct 29 '12 at 10:28

1 Answers1

4

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.

Martin James
  • 24,453
  • 3
  • 36
  • 60