title: How can I close the socket in a proper way?
body: <p>This is a simple TCP server. How can i close the socket when the program is terminated?
  I have using try/finally and try to close the socket. But it doesn't run the finally block when I exit the program. </p>
  
  <p>Anyone can have idea on how to close the socket in a proper way?</p>
  
  <pre><code>try {
          socket = new ServerSocket(port);
          System.out.println("Server is starting on port " + port + " ...");
      }catch (IOException e){
          System.out.println("Error on socket creation!");
      }
  
      Socket connectionSocket = null;
      try{
          while(true){            
              try{
                  connectionSocket = socket.accept();
                  Thread t =  new Thread(new ClientConnection(connectionSocket));
                  t.start();
              }catch (IOException e) {
                  System.out.println("Error on accept socket!");
              }
          }
      }finally{
          this.socket.close();
          System.out.println("The server is shut down!");
      }
  </code></pre>