blemale / scaffeine

Thin Scala wrapper for Caffeine (https://github.com/ben-manes/caffeine)
https://github.com/blemale/scaffeine
Apache License 2.0
265 stars 24 forks source link

Question: Is cache.get(key, buildFunct) thread safe? #292

Closed eugeniasimich closed 2 years ago

eugeniasimich commented 2 years ago

I have a simple (no Loading or AsyncLoading) Cache instance. Is cache.get(key, buildFunction) a thread safe operation? I'm concerned about the case when buildFunction has to be run. In my case buildFunction will perform a side effect to return the initialization value. Can two threads race on generating this initial value? Thanks!

ben-manes commented 2 years ago

The method is atomic and thread-safe, and equivalent to ConcurrentHashMap.computeIfAbsent(key, mappingFunction). Multiple calls to the same key will be blocked to allow only one to perform the load and populate the cache. For different keys, the buildFunction will be invoked in parallel so any it may require some internal synchronization if accessing shared state.