Open Source Your Knowledge, Become a Contributor

Technology knowledge has to be shared and made accessible for free. Join the movement.

Create Content

Reader-Writer Locks - Part IV

Can we make it run faster? The answer — in this case — is a joyful yes; we modify the program to use a reader-writer lock:

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
class Shared {
static final Map<String, int[]> cache = new HashMap<>();
private static final ReadWriteLock lock = new ReentrantReadWriteLock();
static final Lock readLock = lock.readLock();
static final Lock writeLock = lock.writeLock();
}
class Writer extends Producer implements Runnable {
public void run() {
Shared.writeLock.lock();
try {
int[] referenceToValue = Shared.cache.get("key");
for (int i = 0; i < referenceToValue.length; i++) {
// Update value in-place; sum will add up to length
referenceToValue[i] = produce();
}
} finally {
Shared.writeLock.unlock();
}
}
}
class Reader extends Consumer implements Runnable {
public void run() {
Shared.readLock.lock();
try {
consume(Shared.cache.get("key"));
} finally {
Shared.readLock.unlock();
}
}
}
// {...}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content