![]() |
VOOZH | about |
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.
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
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: