1

I have configured cache2K with a loader so keys not present in the cache will be retrieved from the backend datastore. My pattern when updating persisted values it to update the database first, and then the cache is updated asynchronously through a database change notification. Is there any way to prevent stale reads between the time from the database update and the cache is notified of the change?

I was thinking of a mechanism where the stale data is kept in cache, but was effectively expired / loaded the next time the entity was retrieved from cache. I want to keep the key in the cache but force a load when anyone attempts to access the value. I tried setting keepDataAfterExpired = true, however, it seems not to have any effect.

cruftex
  • 5,545
  • 2
  • 20
  • 36
aras03k
  • 11
  • 1

2 Answers2

0

Did you tried to LOCK your table for the duration ? you can read on this site too with more: https://dev.mysql.com/doc/refman/8.0/en/lock-tables.html

0

A possible solution (hibernate is doing it that way) is to store the state with the value. E.g. use a wrapper class for the value:

  abstract class ValueOrUpdating<V> {  }

  class Value<V> extends ValueOrUpdating<V> {
    V value;
  }

  class Updating extends ValueOrUpdating<Void> {
  }

To bypass caching for a key you would do:

  cache.put(key, new Updating();

To access the value:

  V read(K key) {
    ValueOrUpdating<V> v = cache.get(key);
    if (v instanceof Updating) {
      return load(key);
    }
    return ((Value<V>) v).value;
  }

That approach is quite simple and works with every cache.

I tried setting keepDataAfterExpired = true, but that doesnt seem to have any effect

A more sophisticated solution with cache2k could use keepDataAfterExpired and the AdvancedCacheLoader. This way you can exploit other cache2k features like refresh ahead and resilience. Also its possible to avoid calling the loader directly, so the cache statistics will not be flawed. I have put some code for this idea here: https://github.com/cache2k/cache2k-qa/blob/master/java8/src/test/java/StackOverflow63752162Test.java

cruftex
  • 5,545
  • 2
  • 20
  • 36