import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
class Reader extends Consumer implements Runnable {
public void run() {
int[] deepCopy;
synchronized (Shared.cache) {
int[] value = Shared.cache.get("key");
deepCopy = Arrays.copyOf(value, value.length);
}
consume(deepCopy);
}
}
// {
class Writer extends Producer implements Runnable {
public void run() {
synchronized (Shared.cache) {
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 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;
}
}