Sunday, May 1, 2011

Class level lock vs instance level lock

A class level lock is the lock which makes all object of a class to wait until the corresponding lock is not released.

Class A{
static synchronized void foo(){}

Here the method foo is synchronized and hence all the threads on all the objects of the class will wait until the object currently running the foo method completes its execution.

Similarly an instance level lock makes all the threads started using the instance of the class to wait until the lock is not released.

Class A{
//static is missing
synchronized void bar(){}

Here all the threads started from the object which is currently executing the bar method will wait until the current threads completes its execution. Note that other threads of other objects can execute the bar method while another object's thread is executing the bar method.

No comments:

Post a Comment