Today I learned from some JS course what memoization is and tried to implement it in Java. I had a simple recursive function to evaluate n-th Fibonacci number:
l
You can roll your own:
public static V computeIfAbsent(
Map cache,
K key,
Function super K, ? extends V> function
) {
V result = cache.get(key);
if (result == null) {
result = function.apply(key);
cache.put(key, result);
}
return result;
}
This approach assumes you don't have null
values. If you do, just change the logic to use Map.containsKey()
This access works around the problem by making the cache value retrieval and putting of calculated values non-atomic again, which Map::computeIfAbsent
tries to avoid. I.e. the usual race condition problems re-occur. But that might be fine in your case, of course.