Week 118 — What is `ReadWriteLock` and how can an application make use of it?
Question of the Week #118
What is
ReadWriteLock
and how can an application make use of it?1 Reply
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class ReadWriteLockExample {
private final ReadWriteLock lock = new ReentrantReadWriteLock();
private int value;
public int readValue() {
lock.readLock().lock();
try {
return value;
} finally {
lock.readLock().unlock();
}
}
public void writeValue(int newValue) {
lock.writeLock().lock();
try {
value = newValue;
} finally {
lock.writeLock().unlock();
}
}
public static void main(String[] args) {
ReadWriteLockExample example = new ReadWriteLockExample();
Runnable reader = () -> {
System.out.println("Read value: " + example.readValue());
};
Runnable writer = () -> { example.writeValue(42); System.out.println("Value updated to 42"); }; Thread writerThread = new Thread(writer); Thread readerThread1 = new Thread(reader); Thread readerThread2 = new Thread(reader);
writerThread.start(); readerThread1.start(); readerThread2.start(); } }
Runnable writer = () -> { example.writeValue(42); System.out.println("Value updated to 42"); }; Thread writerThread = new Thread(writer); Thread readerThread1 = new Thread(reader); Thread readerThread2 = new Thread(reader);
writerThread.start(); readerThread1.start(); readerThread2.start(); } }
Submission from mlodysimple