1

What's the difference between:

public synchronized void test(){}

and

public void test() {
   synchronized(Sample.class){}
}
Mureinik
  • 297,002
  • 52
  • 306
  • 350
ward
  • 31
  • 3
  • 1
    https://docs.oracle.com/javase/tutorial/essential/concurrency/locksync.html – QuakeCore Dec 07 '14 at 07:33
  • possible duplicate of [Synchronized block lock object question](http://stackoverflow.com/questions/3369287/synchronized-block-lock-object-question) – Jatin Dec 07 '14 at 07:34

3 Answers3

5

To make the difference more clear, the first can be rewritten as:

public void test() {    
   synchronized(this){    
   }    
}

The difference is that the first is synchronized on the instance of the class, whereas the second is synchronized on the class itself.

In the first case, two threads can simultaneously be executing test() on two instances of your class. In the second, they can't.

NPE
  • 486,780
  • 108
  • 951
  • 1,012
1

Declaring a an instance method synchronized is just syntactic sugar that's equivalent to having a synchronized (this) block. In other words, only a single thread can execute the method on this instance at a single point of time.

synchronized (Sample.class) means that all instances of this class share a single lock object (the class object itself), and only a single thread can execute this method on any instance at a single point in time.

Mureinik
  • 297,002
  • 52
  • 306
  • 350
1

To complete @NPE's answer -

a synchronized method is actually a method that is synchronized on the object the method "belongs" to. Whether it's an instance object or the class object itself.

Therefore:

class Sample {
    public synchronized void test(){}
}

is equivalent to

class Sample {
    public void test() {
        synchronized(this) {}
    }
}

while

class Sample {
    public void test() {
       synchronized(Sample.class){}
    }
}

is equivalent to:

class Sample {
    public static synchronized void test(){}
}
Elist
  • 5,313
  • 3
  • 35
  • 73
  • Thanks for replying. But why static? – ward Dec 09 '14 at 09:16
  • When you synchronize on the `Sample.class` object from within the `Sample` class, it's the same as synchronizing a static method in the `Sample` class. That's the point of my answer - a `synchronized` method is actually a method that is `synchronized` on the object the method "belongs" to. Whether it's an instance object or the class object itself. Are you familiar with the `static` concept? – Elist Dec 09 '14 at 09:36