Overview
The Read-Write Lock Design Pattern is used to manage concurrent access to a shared resource by multiple threads. It allows multiple readers to access the resource simultaneously, but ensures exclusive access for writers.
Key Characteristics
- Allows multiple threads to read the resource concurrently.
- Ensures exclusive access for writing, blocking other readers and writers during the write operation.
- Improves performance in scenarios with frequent reads and infrequent writes.
Implementation
The following is an example of a Read-Write Lock implementation in Java:
import java.util.concurrent.locks.ReentrantReadWriteLock;
class SharedResource {
private int value = 0;
private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
public void write(int newValue) {
lock.writeLock().lock();
try {
System.out.println(Thread.currentThread().getName() + " is writing " + newValue);
value = newValue;
Thread.sleep(1000); // Simulate write operation
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.writeLock().unlock();
}
}
public int read() {
lock.readLock().lock();
try {
System.out.println(Thread.currentThread().getName() + " is reading " + value);
Thread.sleep(500); // Simulate read operation
return value;
} catch (InterruptedException e) {
e.printStackTrace();
return -1;
} finally {
lock.readLock().unlock();
}
}
}
public class ReadWriteLockDemo {
public static void main(String[] args) {
SharedResource resource = new SharedResource();
Runnable reader = () -> {
for (int i = 0; i < 5; i++) {
resource.read();
}
};
Runnable writer = () -> {
for (int i = 0; i < 5; i++) {
resource.write(i);
}
};
Thread writerThread = new Thread(writer, "Writer");
Thread readerThread1 = new Thread(reader, "Reader-1");
Thread readerThread2 = new Thread(reader, "Reader-2");
writerThread.start();
readerThread1.start();
readerThread2.start();
}
}
When to Use
- When multiple threads need to read a shared resource concurrently without blocking each other.
- When write operations are infrequent compared to read operations.
Advantages
- Improves performance in read-heavy scenarios by allowing concurrent reads.
- Ensures thread safety for shared resources.
Disadvantages
- Introduces complexity in managing locks and ensuring fairness.
- May cause starvation for writers if readers dominate the resource.