Muhammad Khojaye wrote:
John WongBong wrote:What is the difference between acquiring lock on a CLASS and OBJECT (instance) of that class
// instance level
1. Synchronize(this) or Synchronize(object)
It will synchronize on current instance. That means only one thread can access each instance. (you always have one instance per thread). However, threads will not block each other and several threads can execute as long as they access different instances.
This part is correct, except the 'you always have one instance per thread' and after. If you pass the same object to multiple threads, then you have one object per multiple threads, which is why this mechanism is useful. You only are forced into 'one instance per thread' if you use the Thread object itself as the lock, which is not a good idea for several reasons. Otherwise, it is up to you how many instances you have and how many threads have access to them.
Muhammad Khojaye wrote:// class level
2. Synchronize(MyClass.class)
It will synchronize on class level which is on class of current object. Here only one thread can access any instances of this class. All instance of this class will share lock.
This part is not correct at all. Synchronizing on a Class is exactly like synchronizing on an instance - but the instance you are synchronizing on is an instance of java.lang.Class<MyClass>. It does not block access to any instances of the MyClass, nor does it affect any synchronized blocks using an instance of MyClass as a lock.
The key concept is: to make synchronization and signaling schemes work, you need to be working with the same lock. That could be an instance of an arbitrary Object, or it could be an instance of a java.lang.Class. When you use synchronized(this) it uses the current object, when you use a synchronized instance method it does the same. When you use a synchronized static method it uses the Class instance representing the class the method belongs to. To synchronize properly with a static synchronized method you need to use the same instance of Class.