BAEL-1464 Guava Memoizer (#3420)
* BAEL-1464 Guava Memoizer * Update codes based on code review and discussion in JIRA
This commit is contained in:
committed by
Grzegorz Piwowarek
parent
829c0414fe
commit
d1a4848cb4
@@ -0,0 +1,17 @@
|
||||
package org.baeldung.guava.memoizer;
|
||||
|
||||
import java.math.BigInteger;
|
||||
import java.util.Random;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
public class CostlySupplier {
|
||||
|
||||
public static BigInteger generateBigNumber() {
|
||||
try {
|
||||
TimeUnit.SECONDS.sleep(2);
|
||||
} catch (InterruptedException e) {
|
||||
}
|
||||
return new BigInteger("12345");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package org.baeldung.guava.memoizer;
|
||||
|
||||
import com.google.common.cache.CacheBuilder;
|
||||
import com.google.common.cache.CacheLoader;
|
||||
import com.google.common.cache.LoadingCache;
|
||||
|
||||
import java.math.BigInteger;
|
||||
|
||||
public class Factorial {
|
||||
|
||||
private static LoadingCache<Integer, BigInteger> memo = CacheBuilder.newBuilder()
|
||||
.build(CacheLoader.from(Factorial::getFactorial));
|
||||
|
||||
public static BigInteger getFactorial(int n) {
|
||||
if (n == 0) {
|
||||
return BigInteger.ONE;
|
||||
} else {
|
||||
return BigInteger.valueOf(n).multiply(memo.getUnchecked(n - 1));
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package org.baeldung.guava.memoizer;
|
||||
|
||||
import com.google.common.cache.CacheBuilder;
|
||||
import com.google.common.cache.CacheLoader;
|
||||
import com.google.common.cache.LoadingCache;
|
||||
|
||||
import java.math.BigInteger;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
public class FibonacciSequence {
|
||||
|
||||
private static LoadingCache<Integer, BigInteger> memo = CacheBuilder.newBuilder()
|
||||
.maximumSize(100)
|
||||
.build(CacheLoader.from(FibonacciSequence::getFibonacciNumber));
|
||||
|
||||
public static BigInteger getFibonacciNumber(int n) {
|
||||
if (n == 0) {
|
||||
return BigInteger.ZERO;
|
||||
} else if (n == 1) {
|
||||
return BigInteger.ONE;
|
||||
} else {
|
||||
return memo.getUnchecked(n - 1).add(memo.getUnchecked(n - 2));
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user