I am trying to learn caching and I tried this:
public static <T, U, R> BiFunction<T, U, R> cached(BiFunction<T, U, R> bifunc) {
Cache<Pair<T,U>, R> cache = new Cache<Pair<T,U>, R>(DEFAULT_CACHE_SIZE);
System.out.println("Cache Size: "+cache.size());
return (t, u) -> {
Pair<T,U> pairKey = new Pair<T,U>(t,u);
Function<Pair<T,U>, R> something = input -> {
return bifunc.apply(input.get_first(), input.get_second());
};
return cache.computeIfAbsent(pairKey, something);
};
}
For my cache and this to get the actual result:
BiFunction<BigInteger, BiFunction, BigInteger> fibHelper = cached((n, f) -> {
if (n.compareTo(BigInteger.TWO) <= 0) return BigInteger.ONE;
return ((BigInteger) (f.apply(n.subtract(BigInteger.ONE), f)))
.add((BigInteger)f.apply(n.subtract(BigInteger.TWO), f));
});
Function<BigInteger, BigInteger> fib = (n) -> fibHelper.apply(n,fibHelper);
BigInteger large = fib.apply(BigInteger.valueOf(3L));
I've tested it to run with big numbers and I'm getting a ConcurrentModificationException, so I tried to run with low numbers, when I tried to run with input 0 - 2 it works fine, but once I get to 3 and onwards I get a ConcurrentModificationException. I'm using a LinkedHashMap by the way.
I'm fairly new to this, any help?