group-icon
Java Developers
Group for Java developers and programmers. Ask questions and get answers related to Java programming
262 Members
Join this group to post and comment.
Archana Priyadarshini
Archana Priyadarshini
Computer Science
12 Feb 2019

Object level locking and class level locking in java

There are two types of locking in Java:

Object level locking means you want to synchronize non static method or block so that it can be accessed by only one thread at a time for that instance. It is used if you want to protect non static data.

Class level locking means you want to synchronize static method or block so that it can be accessed by only one thread for whole class. If you have 10 instances of class, only one thread will be able to access only one method or block of any one instance at a time. It is used if you want to protect static data.

AdhikariHarika Reshma
AdhikariHarika Reshma
Computer Science
2mos ago

In Synchronization there are two types of locks in threads:

1.Object Level locking:Every object in java has unique block.Whenever we are using synchronized keyword the only lock concept will come into picture.If a thread wants to execute synchronized method on the given object,first it has to get lock of that object.Once thread got the lock then it is allowed to execute any synchronized method on that object.Once method execution completes automatically thread releases the lock.Acquiring and releasing the lock internally is taken care by JVM and programmer is not responsible for these activities.It should always be done to make instance level data thread safe.

object level locking can be done in various ways:

public class Demo
{
  public synchronized void demoMethod(){}
}
or 
public class Demo
{
  public void demoMethod(){
    synchronized(this)
     {
  
      }
   }
}

2.Class Level locking:Every class in java has a unique block which is nothing but class level lock.If  a thread wants to execute a static synchronized method then thread requires class level lock.Once  a thread got the class level lock,then it is allowed to execute any static synchroized method of that class.Once method execution completes automatically thread releases the lock.It should  always be done to make static data thread safe.

Various ways for class level locking:

public class Demo
{
   //Method is static
   public synchronized static void demoMethod(){
   }
}
or
public class Demo
{
   private final static Object lock=new Object();
   
   public void demoMethod()
   {
      //lock object is static
      synchronized(lock)
      {
        ------
       }
   }
}