Types of Locks
About
1. Object-Level Lock
Example 1
public class MyObject {
public synchronized void methodA() {
System.out.println(Thread.currentThread().getName() + " entered methodA");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {}
System.out.println(Thread.currentThread().getName() + " exiting methodA");
}
public synchronized void methodB() {
System.out.println(Thread.currentThread().getName() + " entered methodB");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {}
System.out.println(Thread.currentThread().getName() + " exiting methodB");
}
}
public class Test {
public static void main(String[] args) {
MyObject obj = new MyObject();
Thread t1 = new Thread(() -> obj.methodA(), "T1");
Thread t2 = new Thread(() -> obj.methodB(), "T2");
t1.start();
t2.start();
}
}
/*
T1 entered methodA
T1 exiting methodA
T2 entered methodB
T2 exiting methodB
*/Example 2
Equivalent Using Explicit Lock
2. Class-Level Lock (Static Synchronization)
Example
Equivalent Using Explicit Lock
3. Method-Level Lock
Example (Instance Method)
Example (Static Method)
4. Block-Level Lock
Example (Object-Level)
Example (Class-Level)
5. Reentrant Lock
Example
6. Fair and Unfair Locks
Example
7. Read-Write Lock
Example
8. Stamped Lock
Example
9. Spin Lock
Example
Comparison
Lock Type
Scope
Use Case
Pros
Cons
Last updated