title: How to delete a thread in Java
body: <p>Here is the important part of my Server class:</p>
  
  <pre><code>        @SuppressWarnings("resource")
          ServerSocket server = new ServerSocket(8000);
  
          while (true)
          {                                               
              Socket s = server.accept();             
              System.out.println("Client connected from " + s.getLocalAddress().getHostName());   
  
              Client chat = new Client(s);
              Thread t = new Thread(chat);
              t.start();
          }
  </code></pre>
  
  <p>As you can see, it creates a new Instance of my Client-Class, which is a thread, everytime a new connection is being established. Here is the important part of my client-class:</p>
  
  <pre><code>        @SuppressWarnings("resource")
          Scanner in = new Scanner(socket.getInputStream());
          PrintWriter out = new PrintWriter(socket.getOutputStream());
          String newLine = null;
  
          while (true)
          {
              try{
                  newLine = in.nextLine();
              }
              catch(NoSuchElementException io){
                  //Delete this instance
              }
              if(clientName==null){
                  clientName = newLine;
              }
              else{
                  out.println(clientName+":  "+newLine);
                  out.flush();
              }
          }
  </code></pre>
  
  <p>Right now, I am catching a disconnect of a client with a try/catch, which reacts to missing nextLine of my socket inputstream. As soon as the client closes his chat client, it will jump into the catch clause everytime, considering that there is no inputstream anymore.</p>
  
  <p>However, due to performance issues, I would now like to remove this Client-Instance, considering that it isn't being used anymore. However, I don't really have any idea how to do this.</p>
  
  <p>I had one idea so far:
   Make my client-class observable, and listen to it in my Server class. As soon as I enter the catch clause, I will notify my observer, which is my Server-class in this case, and tell it to set the reference on this Client-Instance to null, effectively removing any references and leaving it to be dealt with by the Garbage collector.</p>
  
  <p>However, I feel that this is not the way to go here, but honestly, I can't think of any other option right now.</p>
  
  <p>Any tips?</p>