title: Why socket is being closed in run method?
body: <p>Server:</p>
  
  <pre><code>import java.io.IOException;
  import java.net.ServerSocket;
  import java.net.Socket;
  import java.util.concurrent.ExecutorService;
  import java.util.concurrent.Executors;
  
  public final class Server {
  
  public static void main(String[] args) {
      new Server().start();
  }
  
  public void start() {
  
      ExecutorService executorService = Executors.newFixedThreadPool(10);
      try (ServerSocket serverSocket = new ServerSocket(1200)) {
          while (true) {
              try (Socket socket = serverSocket.accept()) {
                  executorService.submit(new SocketHandler(socket));
              } catch (IOException e) {
                  System.out.println("Error accepting connections");
              }
          }
      } catch (IOException e) {
          System.out.println("Error starting server");
      }
  }
  
  public final class SocketHandler implements Runnable {
  
      private final Socket socket;
  
      public SocketHandler(Socket connection) {
          this.socket = connection;
          System.out.println("Constructor: is socket closed? " + this.socket.isClosed());
      }
  
      @Override
      public void run() {
          System.out.println("Run method: is socket closed? " + this.socket.isClosed());
      }
  }
  }
  </code></pre>
  
  <p>Client:</p>
  
  <pre><code>import java.io.IOException;
  import java.net.Socket;
  
  public final class Client{
  
  public static void main(String[] args) {
  
      try (Socket socket = new Socket("localhost", 1200)) {
      } catch (IOException e) {}
  }
  </code></pre>
  
  <p>Output: </p>
  
  <pre><code>Constructor: is socket closed? false
  Run method: is socket closed? true
  </code></pre>
  
  <p>As you can see from output, when run method is invoked <code>socket</code> is closed, but in constructor it was opened. </p>
  
  <p>Question: How to prevent socket being closed in run method, so that I can access its output stream?</p>