title: How to synchronize or lock upon variables in Java?
body: <p>Let me use this small and simple sample:</p>
  
  <pre><code>class Sample {
      private String msg = null;
  
      public void newmsg(String x){
          msg = x;
      }
  
      public String getmsg(){
          String temp = msg;
          msg = null;
          return temp;
      }
  }
  </code></pre>
  
  <p>Let's assume the function <code>newmsg()</code> is called by other threads that I don't have access to. </p>
  
  <p>I want to use the synchonize method to guarantee that the string <code>msg</code> is only used by one function per time. In other words, function <code>newmsg()</code> cannot run at the same time as <code>getmsg()</code>.</p>