title: Multi-threaded Java server vs safe publication
body: <p>When you google for <em>multi-threaded java server</em>, most of the time you'll get a solution based on a following pattern:</p>
  
  <pre><code>public class MultiThreadServer implements Runnable {
    private Socket socket;
  
    MultiThreadServer(Socket socket) {
      this.socket = socket;
    }
  
    public static void main(String args[]) throws Exception {
      ServerSocket serverSocket = new ServerSocket(4444);
      while (true) {
        new Thread(new MultiThreadServer(serverSocket.accept())).start();
      }
    }
  
    public void run() {
      // ...
      PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
      BufferedReader in = new BufferedReader(
                  new InputStreamReader(
                  socket.getInputStream()));
      // ...
    }
  }
  </code></pre>
  
  <p>How does that relate to safe publication idioms presented in <em>Java Concurrency in Practice</em>?</p>
  
  <blockquote>
    <p>To publish an object safely, both the
    reference to the object and the
    object's state must be made visible to
    other threads at the same time. A
    properly constructed object can be
    safely published by:</p>
    
    <ul>
    <li>Initializing an object reference from
    a static initializer.</li>
    <li>Storing a
    reference to it into a volatile field.</li>
    <li>Storing a reference to it into a final
    field. </li>
    <li>Storing a reference to it into
    a field that is properly guarded by a
    (synchronized) lock.</li>
    </ul>
  </blockquote>
  
  <p>Is it really safe to use <code>socket</code> within <code>run()</code> method without any extra synchronization, is it safely published? Please do write more than just <em>yes</em> or <em>no</em>.</p>