Prabhu R
Prabhu R

Reputation: 14222

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)
    {
      ....
    }
  }

}

Upvotes: 2

Views: 1130

Answers (5)

AlexR
AlexR

Reputation: 115328

The parameter of synchronized block is needed to be able to create several "named" blocks. So using special lock object is probably more flexible: you can create lock1 and lock2 in future.

Yet another aspect is waiting and notification. You can say lock.wait() and then lock.notfify() from another thread. In this case you can also use both ways (special lock object or A.class as a lock).

Upvotes: 1

JB Nizet
JB Nizet

Reputation: 691635

In the first case, you synchronize on a public object (A.class), and so other parts of the application might cause problems because they also synchronize on A.class.

In the second case, you synchronize on a private lock object, and are thus sure that nobody else uses the the lock to synchronize access to something else.

Moreover, as indicated in other answers, all the instances of the class will be synchronized on the same lock with the first solution, whereas each instance will have its own lock with the second solution.

The second solution is thus much preferred (although the lock object should be final).

Upvotes: 1

bmargulies
bmargulies

Reputation: 100013

Lock is an ordinary field. So there is one of it for each instance of 'A'. A.class is global to the whole JVM. So the two blocks have completely different semantics. The version with 'lock' says, 'only one thread can be in this block for this instance of A'. The version with A.class says 'only one thread can be in this block for any instance of A.

Upvotes: 1

Andrey Adamovich
Andrey Adamovich

Reputation: 20663

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.

Upvotes: 7

Brett Walker
Brett Walker

Reputation: 3576

Since A.class is avaliable to others, it is public in effect. If something else uses it to synchronize access to some section of code then your section of code could be blocked. This might be good or bad; but you don't have control over it.

Using an internal object allows you to decare it as private so that you have complete control over where and when it is used. I prefer to use an internal object that I have control.

Upvotes: 3

Related Questions