How do you use ReadWriteLock with a simple code example?

In Java, a ReadWriteLock is part of the java.util.concurrent.locks package, and it allows multiple threads to read a resource simultaneously while providing exclusive access to a single thread for writing. This is useful when a resource is read frequently but modified infrequently.

Below is a simple example of using ReadWriteLock:

import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; public class ReadWriteLockExample { private final ReadWriteLock rwLock = new ReentrantReadWriteLock(); private String sharedResource = "Initial Value"; public String read() { rwLock.readLock().lock(); try { return sharedResource; } finally { rwLock.readLock().unlock(); } } public void write(String newValue) { rwLock.writeLock().lock(); try { sharedResource = newValue; } finally { rwLock.writeLock().unlock(); } } public static void main(String[] args) { ReadWriteLockExample example = new ReadWriteLockExample(); // Start reader threads Runnable reader = () -> { System.out.println("Read: " + example.read()); }; // Start writer thread Runnable writer = () -> { example.write("New Value"); System.out.println("Wrote: New Value"); }; Thread writerThread = new Thread(writer); Thread readerThread1 = new Thread(reader); Thread readerThread2 = new Thread(reader); writerThread.start(); readerThread1.start(); readerThread2.start(); } }

ReadWriteLock Java concurrency multithreading ReentrantReadWriteLock