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();
}
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?