title: What is the use of taking a lock on an object in synchronized block, if it can be accessed in any other method?
body: <p>If there is a synchronized block which is taking lock on an object, say StringBuilder sb, which one thread is executing this synchronized block in which sb is locked, suppose there is another thread which is calling another method which will try to change the value of sb(not in synchronized block), then, will it be allowed to do that?</p>
  
  <pre><code>public static void main(String[] args) {
      A a = new A();
      new Thread(new MyRunnable(a), "T1").start();
      new Thread(new MyRunnable(a), "T2").start();
  }
  
  static class MyRunnable implements Runnable {
      A a;
  
      public MyRunnable(A a) {
          super();
          this.a = a;
      }
  
      @Override
      public void run() {
          while (true) {
              if ("T1".equals(Thread.currentThread().getName())) {
                  a.m1();
              } else {
                      a.m2();
              }
          }
      }
  }
  
  
  static class A {
  
       StringBuilder abc = new StringBuilder("fdfd");
  
      public void m1() {
  
          synchronized (abc)
          {
  
              System.out.println("abc locked : " + abc);
          try {
              Thread.sleep(10000);
          } catch (InterruptedException e) {
              e.printStackTrace();}
          System.out.println("abc released: " + abc);
          }
  
      }
  
      public void m2() {
          System.out
                  .println(Thread.currentThread().getName() + "    running");
  
          System.out.println("trying to access abc");
          abc.append("A");
          System.out.println("abc accessed");
          try {
              Thread.sleep(5000);
          } catch (InterruptedException e) {
              e.printStackTrace();}
      }
  }
  
  }
  </code></pre>
  
  <p>I thought locking an object would not allow to change that object as well from being modified or accessed. But, from output I am seeing the locked object can be modified:</p>
  
  <p>OUTPUT:</p>
  
  <pre><code>    abc locked : fdfd
      T2    running
      trying to access abc
      abc accessed
      T2    running
      trying to access abc
      abc accessed
      T2    running
      trying to access abc
      abc released: fdfdAA
      abc accessed
      abc locked : fdfdAAA
      T2    running
  </code></pre>
  
  <p>I am not getting this, can anybody please explain this. What is the use of taking a lock on an object? Is it just because wait/notify/notifyAll methods?</p>