title: Does synchronized (this) lock only the synchronized block or all the "this" code?
body: <pre><code>public class ObjectCounter {
      private static long numOfInstances = 0;
      public ObjectCounter(){
          synchronized(this){
          numOfInstances++;
          }
      }
      **public static synchronized long getCount(){
          return numOfInstances;
      }**
  //vs//
      **public static long getCount(){
          return numOfInstances;
      }**
  }
  </code></pre>
  
  <p>if I'll run few threads, some of them call the static function <code>getCount()</code> and some of them create new instances. I want to get in each call to <code>getCount()</code> the real number of instances at the time.</p>
  
  <ol>
  <li>Is there a difference between the two options in the code?</li>
  <li>If I lock "<code>this</code>" shouldn't it mean that I can't call <code>getCount()</code> until the constructor exits the synchronized block (lets say if I don't write synchronize on the getCount()).</li>
  <li>if I do a synchronized block in some place in the code, does it lock only the synchronized block or all the "<code>this</code>" code?</li>
  <li>From here down EDIT: thank you all, it was very helpful, but I have a few more questions following your answers.</li>
  <li>If I understand correctly, the synchronized(this) block doesn't effect (or connected to) the static synchronized function (in lock terms not the numOfInstances increment)?</li>
  <li>is there a better option to make the increment and the getCount() function Thread-safe? (like open a static object and do synchronized(obj) instead synchronized(this) - friend suggested).</li>
  <li>If I had a f1() method (non-static) in ObjectCounter class, while one thread is in the synchronized(this) can other thread enter f1() block (not a synchronized class or have synchronized block inside)?</li>
  <li>If I had a f1() method (non-static) and f2() method (non-static) in ObjectCounter, in f1() I have synchronized(this) block. while one thread is in the synchronized(this) block, can other thread enter f1() block (not a synchronized class or have synchronized block inside)? (lets say both of the threads "working" on the same instance)</li>
  </ol>
  
  <p>`</p>