ef2011 ef2011 - 1 year ago 74
Java Question

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

I read somewhere that

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

Answer Source

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, perhaps) from getting into an inconsistent state .

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download