Skip to content

refreshAfterWrite returns stale value forever with long load times #175

@panghy

Description

@panghy

We have observed that Caffeine may be stuck in a state where it constantly returns the old value if the loading time of a value is longer than the refreshAfterWrite time. We ran this in 2.4.0.

The following code demonstrates the issue:

 public static void main(String[] args) throws InterruptedException {
    AtomicInteger atomicInteger = new AtomicInteger(1);
    LoadingCache<String, Integer> cache = Caffeine.newBuilder().
        refreshAfterWrite(1, TimeUnit.SECONDS).build(new CacheLoader<String, Integer>() {
      @CheckForNull
      @Override
      public Integer load(@Nonnull String s) throws Exception {
        log.info("calling load");
        long sleepMs = (long) (Math.random() * 10000) + 5000;
        log.info("sleep for: " + sleepMs);
        Thread.sleep(sleepMs);
        log.info("slept for: " + sleepMs);
        int toReturn = atomicInteger.incrementAndGet();
        log.info("returning: " + toReturn);
        return toReturn;
      }
    });
    while (true) {
      int result = cache.get("hello");
      if (atomicInteger.get() != result) {
        log.info("got: " + result + " from cache but atomic integer is: " + atomicInteger.get());
      }
    }
  }

The output suggests that cache.get("hello") returns the value of 2 where as the atomic integer is returning a value much higher than that. In fact, after running for a long time, cache.get("hello") continues to return a value of 2 whereas the atomic integer has been incremented to the thousands.

Aug 03, 2017 6:17:49 PM queryserver.TestCaffeine main
INFO: got: 2 from cache but atomic integer is: 12983

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions