Back
Close

Computing with Data

elgeish
31.1K views

Reader-Writer Locks - Part II

In order to return the correct value, we may want to make the cache a mutually exclusive resource by making the following changes to the program:

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
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 Reader extends Consumer implements Runnable {
public void run() {
synchronized (Shared.cache) {
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