#492 Non-Blocking Cache with Dirty-Read Protection

Companies:
Ozon
Themes:
JavaConcurrencyCode Review

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 N constant reader threads;
  • There is one thread that updates the cache;
  • A reader must be protected from a dirty read. If a mutation A -> B is occurring, the reader must see only a complete state, either A or B, 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

Mentor
Answer as you would in a real interview. I’ll ask follow-up questions, then compare your answer with the reference answer and show your accuracy as a %.
Sign in to start the dialogue The mentor keeps the context of the current question and your previous messages.
Sign in