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?
Your data structures are not Thread-Safe.
ConcurrentModificationException is usually received when two threads are using/overriding the same object (usually data structures), or when an object is changed during iterating it (thanks Thomas Kläger).
I didn't understand what do you mean by
In which context?
BTW, LinkedHashMap is not concurrent-safe. If you want concurrent-safe data structures, you should use java.util.Concurrent package.
As rzwitserloot said, please provide full implementation or clearer explanation.