Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Concurrent Patterns and Best Practices

You're reading from   Concurrent Patterns and Best Practices Build scalable apps in Java with multithreading, synchronization and functional programming patterns

Arrow left icon
Product type Paperback
Published in Sep 2018
Publisher Packt
ISBN-13 9781788627900
Length 264 pages
Edition 1st Edition
Languages
Concepts
Arrow right icon
Author (1):
Arrow left icon
Atul S. Khot Atul S. Khot
Author Profile Icon Atul S. Khot
Atul S. Khot
Arrow right icon
View More author details
Toc

Reader or writer locks


A readers–writer(RW) or shared-exclusivelock is a primitive synchronization that allows concurrent access for read-only operations, as well as  exclusive write operations. Multiple threads can read the data concurrently, but for writing or modifying the data, an exclusive lock is needed.

A writer has exclusive access for writing data. Till the current writer is done, other writers and readers will be blocked. There are many cases where data is read more often than it is written.

The following code shows how we use the locks to provide concurrent access to a Java Map<K, V>. The code synchronizes the internal map, using an RW lock:

public class RWMap<K, V> {
private final Map<K, V> map;
private final ReadWriteLock lock = new ReadWriteLock();
private final RWLock r = lock.getRdLock();
private final RWLock w = lock.getWrLock();

public RWMap(Map<K, V> map) {
this.map = map;
 }

public V put(K key, V value) throws InterruptedException {
w.lock();
try...
lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €18.99/month. Cancel anytime