VOOZH about

URL: https://www.geeksforgeeks.org/java/object-level-lock-in-java/

⇱ Object Level Lock in Java - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Object Level Lock in Java

Last Updated : 24 Apr, 2026

Object-level locking in Java controls concurrent access at the instance level, ensuring safe interaction with object data in multithreaded environments. It allows threads to coordinate execution when working on the same object. This mechanism helps maintain consistency without affecting other object instances.

  • Applied using synchronized on non-static methods or blocks
  • Ensures mutual exclusion only for threads accessing the same object
  • Other threads must wait until the lock is released

Methods of Object Level Lock

There are different ways we can lock the object in the thread as below:

Method 1:

public class GeekClass{
public synchronized void GeekMethod(){}
}

Method 2:

public class GeekClass {
public void GeekMethod(){
synchronized (this) {
// other thread safe code }
}
}

Method 3:


public class DemoClass {
private final Object lock = new Object();
public void demoMethod(){
synchronized (lock) {
// other thread safe code }
}
}

Example : Java program to illustrate Object lock concept


Output
t1
t2
t3
in block t1
in block t3
in block t3 end
in block t1 end
in block t2
in block t2 end


Explanation:

  • Threads t1 and t2 share the same object (g), so they compete for the same object lock and execute the synchronized block one at a time
  • Thread t3 uses a different object (g1), so it gets a separate lock and can execute independently
  • This shows that object-level lock works per object, not per class
Comment