0

I'm trying to use an LRU cache as shown here Java time-based map/cache with expiring keys

My code:

import com.google.common.cache.CacheBuilder
import java.util.concurrent.TimeUnit

fun main(args: Array<String>) {


val cache = CacheBuilder.newBuilder().maximumSize(100).
    expireAfterAccess(10, TimeUnit.HOURS)
    .build<String, String>()


    cache.put("a", "blah")
    val x = cache.getIfPresent("a")
    cache.stats().also { println(it) }
    println(x)

}

Output:

CacheStats{hitCount=0, missCount=0, loadSuccessCount=0, loadExceptionCount=0, totalLoadTime=0, evictionCount=0}
blah

I was expecting hitCount to be 1, rather than 0.

What am I missing here?

nz_21
  • 6,140
  • 7
  • 34
  • 80

1 Answers1

2

You're missing .recordStats() call on CacheBuilder:

Enable the accumulation of CacheStats during the operation of the cache. Without this Cache.stats() will return zero for all statistics.

Grzegorz Rożniecki
  • 27,415
  • 11
  • 90
  • 112