java 31 lines · 6 steps

A thread-safe memoized factorial cache

Caching factorial results in a ConcurrentHashMap so repeated calls skip the BigInteger arithmetic.

Explained by highlit
1import java.util.Map;
2import java.util.concurrent.ConcurrentHashMap;
3import java.math.BigInteger;
4 
5public class FactorialCache {
6 
7 private final Map<Integer, BigInteger> cache = new ConcurrentHashMap<>();
8 
9 public BigInteger factorial(int n) {
10 if (n < 0) {
11 throw new IllegalArgumentException("n must be non-negative: " + n);
12 }
13 return cache.computeIfAbsent(n, this::compute);
14 }
15 
16 private BigInteger compute(int n) {
17 BigInteger result = BigInteger.ONE;
18 for (int i = 2; i <= n; i++) {
19 result = result.multiply(BigInteger.valueOf(i));
20 }
21 return result;
22 }
23 
24 public int cachedEntries() {
25 return cache.size();
26 }
27 
28 public void evict(int n) {
29 cache.remove(n);
30 }
31}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1computeIfAbsent turns a map into a memoization table without manual check-then-put races.
  2. 2ConcurrentHashMap lets multiple threads share a cache safely with no explicit locking.
  3. 3BigInteger keeps factorial results exact even when they overflow primitive integer types.

Related explainers

Share this explainer

Here's the card — post it anywhere.

A thread-safe memoized factorial cache — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code