Sunday, 17 May 2020

Difference between class level and object locking and static object lock


1) Class level locking will lock entire class, so no other thread can access any of other synchronized blocks.

2) Object locking will lock the block but more than one thread can enter this block simultaneously , but only if they are objects of different Threads

3)  In case of static object locking, Only one thread can enter this block of any class. But other threads can access 2nd synchronized blocks


public class SyncEx{

 private static final Object ststicLock = new Object();
 private final Object lock = new Object();

 public void lockingEx() {

    synchronized (ststicLock) {
        // Only one thread can enter this block of any class.. But other threads can access 2nd synchronized blocks
    }

    synchronized (lock) {
        // More than one thread can enter this block simultaneously , but only if they are objects of different Threads
    }

synchronized (SyncEx.class) {
        // Only one thread can enter this block of any class. No other thread will be allowed to access any of the other synchronized blocks
    }
 }
}

No comments:

Post a Comment

Thank You for your valuable comment

Difference between class level and object locking and static object lock

1) Class level locking will lock entire class, so no other thread can access any of other synchronized blocks. 2) Object locking will lo...