Difference between Object level lock and Class level lock in Java

JavaObject Oriented ProgrammingProgramming

In multithreading environment, two or more threads can access the shared resources simultaneously which can lead the inconsistent behavior of the system. Java uses concept of locks to restrict concurrent access of shared resources or objects. Locks can be applied at two levels −

  • Object Level Locks − It can be used when you want non-static method or non-static block of the code should be accessed by only one thread.
  • Class Level locks − It can be used when we want to prevent multiple threads to enter the synchronized block in any of all available instances on runtime. It should always be used to make static data thread safe. 
Sr. No.
Key
Object Level Lock
Class Level Lock

1

Basic 

It can be used when you want non-static method or non-static block of the code should be accessed by only one thread

It can be used when we want to prevent multiple threads to enter the synchronized block in any of all available instances on runtime

2

Static/Non Static 

It should always be used to make non-static data thread safe. 

It should always be used to make static data thread safe. 


3

Number of Locks 

Every object the class may have their own lock

Multiple objects of class may exist but there is always one class’s class object lock available

Example of Class Level Lock

public class ClassLevelLockExample {
   public void classLevelLockMethod() {
      synchronized (ClassLevelLockExample.class) {
         //DO your stuff here
      }
   }
}

Example of Object Level Lock

public class ObjectLevelLockExample {
   public void objectLevelLockMethod() {
      synchronized (this) {
         //DO your stuff here
      }
   }
}
raja
Published on 21-Jan-2020 14:40:57
Advertisements