Read-Write Lock Design Pattern

Back To Index

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

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

Advantages

Disadvantages

Back To Index