TheAlgorithms/Java · error · IllegalArgumentException

Eviction strategy must not be null

Error message

Eviction strategy must not be null

What it means

Thrown by LIFOCache.Builder.evictionStrategy(EvictionStrategy) when the strategy is null. The strategy's onAccess is called on every get/put; a null would NPE on every cache operation. The builder defaults to ImmediateEvictionStrategy, so this guard only fires when a caller explicitly passes null.

Source

Thrown at src/main/java/com/thealgorithms/datastructures/caches/LIFOCache.java:557

        /**
         * Builds and returns a new {@link LIFOCache} instance with the configured parameters.
         *
         * @return a fully configured {@code LIFOCache} instance
         */
        public LIFOCache<K, V> build() {
            return new LIFOCache<>(this);
        }

        /**
         * Sets the eviction strategy used to determine when to clean up expired entries.
         *
         * @param strategy an {@link EvictionStrategy} implementation; must not be {@code null}
         * @return this builder instance
         * @throws IllegalArgumentException if {@code strategy} is {@code null}
         */
        public Builder<K, V> evictionStrategy(EvictionStrategy<K, V> strategy) {
            if (strategy == null) {
                throw new IllegalArgumentException("Eviction strategy must not be null");
            }
            this.evictionStrategy = strategy;
            return this;
        }
    }
}

View on GitHub (pinned to fdfb9a395b)

Solutions

  1. Omit evictionStrategy() to keep the default ImmediateEvictionStrategy.
  2. Provide a concrete strategy or a no-op: cache -> 0.
  3. Ensure your strategy-selection helper never returns null.

Example fix

// before
builder.evictionStrategy(selectStrategy(mode));
// after
EvictionStrategy<K,V> s = selectStrategy(mode);
if (s != null) builder.evictionStrategy(s);
Defensive patterns

Strategy: validation

Validate before calling

EvictionStrategy<K, V> s = selectStrategy(mode);
if (s != null) builder.evictionStrategy(s);

Type guard

static <K, V> boolean isUsableStrategy(EvictionStrategy<K, V> s) {
    return s != null;
}

Prevention

When it happens

Trigger: builder.evictionStrategy(null); conditional wiring returning null in some branch; DI misconfiguration.

Common situations: Strategy selection by enum with a case returning null; refactoring leaving a null branch; tests resetting the strategy.

Related errors


AI-assisted analysis of TheAlgorithms/Java@fdfb9a395b (2026-08-13). Data as JSON: /api/errors/f01353bccfe67f8c. Report an issue: GitHub.