title: When to use volatile and synchronized
body: <p>I know there are many questions about this, but I still don't quite understand. I know what both of these keywords do, but I can't determine which to use in certain scenarios. Here are a couple of examples that I'm trying to determine which is the best to use.</p>
  
  <p>Example 1:</p>
  
  <pre><code>import java.net.ServerSocket;
  
  public class Something extends Thread {
  
      private ServerSocket serverSocket;
  
      public void run() {
          while (true) {
              if (serverSocket.isClosed()) {
                  ...
              } else { //Should this block use synchronized (serverSocket)?
                  //Do stuff with serverSocket
              }
          }
      }
  
      public ServerSocket getServerSocket() {
          return serverSocket;
      }
  
  }
  
  public class SomethingElse {
  
      Something something = new Something();
  
      public void doSomething() {
          something.getServerSocket().close();
      }
  
  }
  </code></pre>
  
  <p>Example 2:</p>
  
  <pre><code>public class Server {
  
      private int port;//Should it be volatile or the threads accessing it use synchronized (server)?
  
      //getPort() and setPort(int) are accessed from multiple threads
      public int getPort() {
          return port;
      }
  
      public void setPort(int port) {
          this.port = port;
      }
  
  }
  </code></pre>
  
  <p>Any help is greatly appreciated.</p>