Sobes.tech
Junior — Middle

Explain the working principle of read-write lock mechanisms.

sobes.tech AI

Answer from AI

ReadWriteLock is an interface in Java that allows sharing access to a resource among multiple threads, optimizing read and write operations.

Working principle:

  • Multiple threads can simultaneously acquire the read lock if there is no active writer.
  • Only one thread can acquire the write lock, and during this time, no other threads can read or write.

This increases performance in scenarios where read operations significantly outnumber write operations, as reading does not block each other.

Example usage:

import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class SharedData {
    private final ReadWriteLock rwLock = new ReentrantReadWriteLock();
    private int data;

    public int read() {
        rwLock.readLock().lock();
        try {
            return data;
        } finally {
            rwLock.readLock().unlock();
        }
    }

    public void write(int value) {
        rwLock.writeLock().lock();
        try {
            data = value;
        } finally {
            rwLock.writeLock().unlock();
        }
    }
}
Explain the working principle of read-write lock… - sobes.tech