It's complicated for me to articulate a proper title for this. But an example should make it far simpler. Suppose I have this:
final class Cache {
private static final ConcurrentHashMap<String, List<String>> CACHE = ...
static List<String> byName(String name) {
return CACHE.computeIfAbsent(name, x -> // some expensive operation)
}
}
The idea is probably trivial, this acts as a LoadingCache, much like guava or caffeine (in reality it is more complicated, but that is irrelevant to the question).
I would like to be able to tell if this was the first load into the CACHE, or it was a read of an existing mapping. Currently, I do this:
final class Cache {
private static final ConcurrentHashMap<String, List<String>> CACHE = ...
static List<String> byName(String name) {
boolean b[] = new boolean[1];
List<String> result = CACHE.computeIfAbsent(name, x -> {
b[0] = true;
// some expensive operation)
});
if(b[0]) {
// first load into the cache, do X
} else {
// do Y
}
return result;
}
}
This works, but I am afraid I am missing something that ConcurrentHashMap
can offer for me that would allow me to do the same. Thank you.