Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between synchronized(this) and synchronized(ClassName.class)?

I read somewhere that synchronized(this) should be avoided for various reasons. Yet some respectable code that I encountered uses the following in the constructor:

public SomeClass(Context context) {
  if (double_checked_lock == null) {
    synchronized (SomeClass.class) {
      if (double_checked_lock == null) {
        // some code here
      }
    }
  }
}

Is there really a difference between synchronized(this) and synchronized(SomeClass.class)?

like image 265
ef2011 Avatar asked Jan 29 '12 19:01

ef2011


1 Answers

synchronized(this) is synchronized on the current object, so only one thread can access each instance, but different threads can access different instances. E.g. you can have one instance per thread.

This is typically useful to prevent multiple threads from updating an object at the same time, which could create inconsistent state.

synchronized(SomeClass.class) is synchronized on the class of the current object ( or another class if one wished) so only one thread at a time can access any instances of that class.

This might be used to protect data that is shared across all instances of a class (an instance cache, or a counter of the total number of instances, perhaps) from getting into an inconsistent state .

like image 168
DNA Avatar answered Oct 23 '22 04:10

DNA