In Java, a lock is a synchronization mechanism that controls access to shared resources in multithreaded programs. It helps prevent race conditions and ensures thread safety when multiple threads access shared data.
- Exclusive Lock (ReentrantLock): Allows only one thread to hold the lock at a time.
- Read-Write Lock (ReadWriteLock): Allows multiple threads to read simultaneously but requires exclusive access for writing.
Basic usage of a Lock:
Lock lock = new ReentrantLock();
lock.lock(); // Acquire the lock
// Critical section
lock.unlock(); // Release the lock
Types of Locks in Java
Java provides different types of locks to control thread access to shared resources and ensure thread safety in concurrent applications.
1. ReentrantLock
A ReentrantLock allows a thread to acquire the same lock multiple times without releasing it first. This is useful when a method holding a lock calls another method that requires the same lock.
- Only one thread can own the lock at a time.
- The owning thread can acquire it again, but must release it the same number of times.
import java.util.concurrent.locks.ReentrantLock;
class Task {
private final ReentrantLock lock = new ReentrantLock();
public void firstMethod(){
lock.lock();
try{
System.out.println("First lock: "
+ lock.getHoldCount());
// Reacquire the same lock in another method
secondMethod();
System.out.println("After second method: "
+ lock.getHoldCount());
}
finally{
lock.unlock();
}
System.out.println("After releasing: "
+ lock.getHoldCount());
}
public void secondMethod(){
lock.lock();
try{
System.out.println("Second lock: "
+ lock.getHoldCount());
}
finally{
lock.unlock();
}
}
}
public class GFG{
public static void main(String[] args){
Task task = new Task();
task.firstMethod();
}
}
Output:
First lock: 1
Second lock: 2
After second method: 1
After releasing: 0Explanation:
- firstMethod() acquires the lock, increasing its hold count to 1.
- It calls secondMethod(), where the same thread acquires the lock again, increasing the count to 2.
- secondMethod() releases one hold, decreasing the count to 1.
- firstMethod() releases the remaining hold, making the count 0 and freeing the lock.
This is called reentrancy. The same thread can acquire a lock it already owns without blocking itself. The lock becomes available to other threads only after all its holds are released.
2. ReadWriteLock
A ReadWriteLock allows multiple threads to read a resource concurrently, but only one thread to write, ensuring no reads happen during writing.
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
class SharedData{
private final List<String> list = new ArrayList<>();
private final ReadWriteLock rwLock
= new ReentrantReadWriteLock();
private final Lock readLock = rwLock.readLock();
private final Lock writeLock = rwLock.writeLock();
// Writer
public void add(String value){
writeLock.lock();
try{
list.add(value);
System.out.println(
Thread.currentThread().getName()
+ " added: " + value);
}
finally{
writeLock.unlock();
}
}
// Reader
public void read(int index){
readLock.lock();
try{
if (index < list.size()){
System.out.println(
Thread.currentThread().getName()
+ " read: " + list.get(index));
}
}
finally{
readLock.unlock();
}
}
}
public class GFG{
public static void main(String[] args){
SharedData data = new SharedData();
// Writers
Thread writer1
= new Thread(() -> data.add("Hi"), "Geek-1");
Thread writer2 = new Thread(
() -> data.add("Hello"), "Geek-2");
// Readers
Thread reader1
= new Thread(() -> data.read(0), "Geek-1");
Thread reader2
= new Thread(() -> data.read(1), "Geek-2");
writer1.start();
writer2.start();
reader1.start();
reader2.start();
}
}
Output
Geek-1 added: Hi Geek-2 added: Hello Geek-1 read: Hi Geek-2 read: Hello
Explanation: ReadWriteLock allows multiple threads to read simultaneously but only one thread to write at a time. This ensures safe and efficient access to shared data.
Methods in the Lock Interface
The Lock interface provides several methods for acquiring and releasing locks:
| Method | Description |
|---|---|
| void lock() | Acquires the lock if available; blocks if the lock is held by another thread. |
| void lockInterruptibly() | Acquires the lock unless the thread is interrupted while waiting. |
| void unlock() | Releases the lock. |
| Condition newCondition() | Returns a Condition object associated with the lock. Useful for wait/notify. |
| boolean tryLock() | Attempts to acquire the lock immediately, returning true if successful. |
| boolean tryLock(long time, TimeUnit unit) | Tries to acquire the lock within a specified timeout. Returns true if successful. |