Synchronization and locks · Topic 6 of 8
ReadWriteLock
Definition​
A ReadWriteLock allows many threads to read at the same time, but only one thread to write, and no readers while it writes. It speeds up data that is read often and changed rarely.
Example code​
A small cache with shared reads and exclusive writes
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReentrantReadWriteLock;
class Cache {
private final Map<String, String> data = new HashMap<>();
private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
String get(String key) {
lock.readLock().lock(); // many readers can hold this at once
try { return data.get(key); }
finally { lock.readLock().unlock(); }
}
void put(String key, String value) {
lock.writeLock().lock(); // a writer waits for readers and blocks them
try { data.put(key, value); }
finally { lock.writeLock().unlock(); }
}
}
class Demo {
public static void main(String[] args) {
Cache cache = new Cache();
cache.put("city", "Pune");
System.out.println(cache.get("city"));
}
}
// Output:
// Pune
Finished this page? Track your progress (saved only in your browser).