Since Java 9 HashMap.computeIfAbsent() throws ConcurrentModificationException on attempt to memoize recursive function results

后端 未结 2 1892
南方客
南方客 2021-02-12 13:00

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         


        
2条回答
  •  借酒劲吻你
    2021-02-12 13:49

    You can roll your own:

    public static  V computeIfAbsent(
        Map cache, 
        K key,
        Function 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.

提交回复
热议问题