Wednesday, January 30, 2013

Threads Synchronisation

Synchronized method:

case 1: non-static-methods: If a thread is accessing synchronized method of an object, then any another thread can not access any of the synchronized methods/synchronized blocks of that object.

case 2: static-methods: If synchronized method is declared static and if a thread is accessing that method, then any other thread can not access any of the static synchronized method of that class. the above statement is true even if the objects are different.

Synchronized blocks:

case 1:
Synchronized(this){
...
}

If a thread enters Synchronized block, then no other thread can access synchronized blocks and synchronized methods of that object.  

case 2:
Synchronized(obj){
...
}
If a thread enters the synchronized block as shown above. the lock is acquired on obj. so no other threads can access the synchronized methods and blocks of that obj.

case 3:
Synchronized(obj.class){
...
}
The only difference between the above case and this case is, lock is acquired at class level.

No comments:

Post a Comment