Skip to content

Instantly share code, notes, and snippets.

@mgryszko
Created March 26, 2020 09:19
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mgryszko/3ec20c1346f5d889c658ac5a0e003c2a to your computer and use it in GitHub Desktop.
Save mgryszko/3ec20c1346f5d889c658ac5a0e003c2a to your computer and use it in GitHub Desktop.
Characterisation test of Caffeine refreshable cache
import com.github.benmanes.caffeine.cache.CacheLoader
import com.github.benmanes.caffeine.cache.Caffeine
import com.github.benmanes.caffeine.cache.Ticker
import org.assertj.core.api.Assertions.assertThat
import org.junit.Test
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicInteger
class CaffeineAsyncRefreshableCacheTest {
@Test
fun `refreshable cache works as expected`() {
val loader = SpyingCacheLoader({ "one" }, { "uno" }, { throw IllegalArgumentException() })
val ticker = AdjustableTicker(0)
val cache = Caffeine.newBuilder()
.refreshAfterWrite(1, TimeUnit.NANOSECONDS)
.maximumSize(100)
.ticker(ticker)
.build(loader)
assertThat(cache.get("1")).isEqualTo("one")
ticker.reference = 10
assertThat(cache.get("1")).isIn("one", "uno")
ticker.reference = 20
assertThat(cache.get("1")).isEqualTo("uno")
ticker.reference = 30
assertThat(cache.get("1")).isEqualTo("uno")
ticker.reference = 40
assertThat(cache.get("1")).isEqualTo("uno")
}
class SpyingCacheLoader(vararg val returnValues: () -> String) : CacheLoader<String, String> {
val loads = AtomicInteger(0)
override fun load(key: String): String? {
val nthValue = loads.getAndUpdate { if (it < returnValues.size - 1) it.inc() else it }
return returnValues[nthValue]()
}
}
class AdjustableTicker(var reference: Long) : Ticker {
override fun read(): Long = reference
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment