Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using synchronized block

What is the difference or impact between using the synchronized block as in method1 and method2?

class A
{
  private Object lock = new Object();
  ...
  ...

  private void method1()
  {
    synchronized(A.class)
    {
      .....
    }
  }


  private void method2()
  {
    synchronized(lock)
    {
      ....
    }
  }

}
like image 302
Prabhu R Avatar asked Feb 27 '26 05:02

Prabhu R


1 Answers

In first method all threads that use ANY instance of the class A will be syncronised.

In second method all threads that use THIS instance of the class A will be syncronised.

like image 85
Andrey Adamovich Avatar answered Mar 01 '26 17:03

Andrey Adamovich