#492 Non-Blocking Cache with Dirty-Read Protection
Implement a "cache" that stores a long[] by index.
The cache size is 10 elements.
It implements two methods:
-
void bulkUpdate(Updater updater)— updates values in batches by mutating the current cache state in place; -
long[] bulkRead(int[] indices)— obtains the required long values from the cache by index in a batch.
Conditions:
-
There are
Nconstant reader threads; - There is one thread that updates the cache;
-
A reader must be protected from a dirty read. If a mutation
A -> Bis occurring, the reader must see only a complete state, eitherAorB, but never an intermediate state; - Reading must be non-blocking;
- Writing may be blocking;
-
The input may be assumed to always be valid: not
null, and indices range from 0 through 9.
interface Cache {
// Method for updating the cache through mutation
void bulkUpdate(Updater updater);
// Method that accepts indices to read
long[] bulkRead(int[] indices);
}
// Interface used by cache clients to update it
interface Updater {
void updateCurrentState(long[] currentCacheState);
}
public void main() {
var cache = new SimpleCache();
cache.bulkUpdate(arr -> { arr[0] = 123; arr[1] = 456; });
var cacheValues = cache.bulkRead(new int[]{1, 2});
System.out.println(Arrays.toString(cacheValues));
}
Question review
Sign in to start the dialogue
The mentor keeps the context of the current question and your previous messages.
Sign in
Available with Premium
This is just one of the solutions available with Premium. And more:
- 250+ advanced lectures
- 1300+ practice exercises
- 500+ solutions to problems from real interviews
- Personalized Java Hub certificates
- Expanded access to the AI mentor