Back
Close

Computing with Data

elgeish
33.3K views

Reader-Writer Locks - Part I

Here's an example where we produce a dummy value to write to each element of the cached array so that its sum is either 0 (initial value) or its length (after any complete write operation):

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
class Simulator {
static void simulateWork() {
try {
Thread.sleep(3); // simulates work being done
} catch (InterruptedException ex) {
System.out.println(ex);
}
}
}
class Shared {
static final Map<String, int[]> cache = new HashMap<>();
}
class Producer {
protected int produce() {
Simulator.simulateWork();
return 1;
}
}
class Writer extends Producer implements Runnable {
public void run() {
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();
}
}
}
class Consumer {
protected void consume(int[] value) {
int sum = Arrays.stream(value).sum();
if (sum != 0 && sum != value.length) {
throw new IllegalStateException("Partial sum: " + sum);
}
Simulator.simulateWork();
}
}
class Reader extends Consumer implements Runnable {
public void run() {
consume(Shared.cache.get("key"));
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Create your playground on Tech.io
This playground was created on Tech.io, our hands-on, knowledge-sharing platform for developers.
Go to tech.io
codingame x discord
Join the CodinGame community on Discord to chat about puzzle contributions, challenges, streams, blog articles - all that good stuff!
JOIN US ON DISCORD
Online Participants