Scrivio Interview library
DebuggingIntermediate6 min read · updated 12 November 2026

A service is slow and a profile shows a remote call inside this line: Config c = cache.get(key).orElse(loadFromRemote(key)); Explain the bug.

orElse takes a value, and Java evaluates every method argument before the call, so loadFromRemote(key) runs on every lookup, even when the cache already holds the config; its result is then simply thrown away. The fix is orElseGet(() -> loadFromRemote(key)), which passes a Supplier that runs only when the Optional is empty. This mistake is common wherever the default is expensive or has side effects, and IDE inspections and static analysis tools can flag method calls passed to orElse.

Why this question is asked

This is one of the most frequent Optional bugs in production code, and it is invisible in functional tests: the result is always correct, only slower and more expensive. It shows up as a cache that never seems to help, a remote service receiving far more traffic than expected, or a profiler showing network calls on what should be a memory lookup. Interviewers ask it because the cause is a basic rule of the Java language, not anything specific to Optional. In this answer, we will recap how Java evaluates method arguments, reproduce the problem, follow the call to see where the remote call happens, fix it, and look at how to prevent it and what a better cache design looks like.

1A Quick Recap: Arguments Are Evaluated Before the Call

When Java calls a method, it first evaluates every argument expression, left to right, and only then runs the method with the resulting values. This is called eager evaluation. So in foo(bar()), bar() always runs before foo starts, whatever foo does with the value.

orElse(T other) is an ordinary method with an ordinary parameter. Writing optional.orElse(loadFromRemote(key)) therefore means: call loadFromRemote(key), take its result, then call orElse with it. orElse has no way to prevent the evaluation, because it happens before orElse even begins.

2Reproducing the Problem

We can see it with a counter standing in for the remote call.

Java
AtomicInteger remoteCalls = new AtomicInteger();
Config loadFromRemote(String key) {
remoteCalls.incrementAndGet();
return remoteConfigClient.fetch(key); // about 80 ms over the network
}
cache.put("pricing", new Config("pricing", 3));
Config c = cache.get("pricing").orElse(loadFromRemote("pricing"));
System.out.println(c.version()); // 3: the cached value is returned
System.out.println(remoteCalls.get()); // 1: the remote call still happened
Step throughA cache hit that still calls the remote service
ServiceCacheRemote config
loadFromRemote(key): evaluated first, as the argument
config v4 (80 ms)
get(key)
Optional[config v3]
orElse(v4) returns v3; v4 is thrown away

5 messages in order. Play them, or step through them one at a time.

The argument to orElse is computed before orElse runs, whether it is needed or not.

Notice that the result is correct. The cached config is returned and the freshly loaded one is discarded, so every functional test passes. The only symptoms are the cost: about 80 ms of latency and one request to the remote service on every lookup, which is exactly what the profiler revealed. A cache with a 99% hit rate now saves nothing.

3The Fix: orElseGet With a Supplier

orElseGet takes a Supplier, a small function that produces the value when asked. Passing a lambda hands over the instructions for loading, not the loaded result, and Optional calls it only when it is empty.

Java
Config c = cache.get(key).orElseGet(() -> loadFromRemote(key));
// cache hit: returns the cached config, remoteCalls stays 0
// cache miss: calls loadFromRemote once and returns its result

Notice that the only change is the method name and the () -> in front of the call. The lambda captures key, which is fine because it is effectively final. After the fix, the profiler shows the remote call only on cache misses, and the remote service's request rate drops to the miss rate.

orElse is still the right method when the default is a constant or a value that already exists, such as orElse(Config.DEFAULT) or orElse("unknown"). Evaluating those costs nothing, and orElse reads slightly more simply.

4Why This Bug Is So Common

The two methods differ by a few characters and look interchangeable in examples that use constants, so people learn orElse first and use it everywhere. The bug is also silent: there is no exception and no wrong result, only cost. It typically appears when the default has a cost or a side effect, such as a remote call, a database query, creating a large object, generating an id, or logging "cache miss". With side effects, it can also cause real errors, for example incrementing a counter, sending a message or consuming a one-time token on every call.

Choosing between orElse and orElseGet
Default expressionUseWhy
"unknown", 0, Config.DEFAULTorElsealready a value; nothing to evaluate
new ArrayList<>()orElseGetallocates on every call otherwise
repository.find(...), remote callorElseGetexpensive; must run only on a miss
anything with side effectsorElseGetthe effect would happen on every call
throwing when absentorElseThrow(supplier)exception built only when needed
If the default is not already a value, it belongs in a Supplier.

5Preventing It and Improving the Cache

Tooling can catch this. IntelliJ IDEA, Sonar and other static analysis tools have inspections that flag method calls or object creation passed to orElse and suggest orElseGet; check the exact rule names in your setup and make sure the rule runs in the build, not only in the IDE. Code review should treat orElse(someMethod(...)) as a question to ask every time.

It is also worth looking at the cache design. Checking the cache and loading on a miss in caller code means every caller must remember the pattern, and nothing stores the loaded value. A loading cache does both in one call. With Caffeine, for example, cache.get(key, k -> loadFromRemote(k)) returns the cached value or loads, stores and returns it, and it ensures that concurrent misses for the same key trigger only one load. Spring's @Cacheable gives a similar effect declaratively.

Java
Cache<String, Config> configs = Caffeine.newBuilder()
.expireAfterWrite(Duration.ofMinutes(5))
.maximumSize(10_000)
.build();
Config c = configs.get(key, this::loadFromRemote); // loads once per key per expiry, then serves from memory

6Follow-up questions

Is orElseGet ever slower than orElse?

In theory it creates a lambda object, but for a non-capturing lambda the JVM reuses one instance, and for a capturing one the allocation is tiny and often optimised away. Compared with a remote call, the difference is nothing. For constants, orElse is preferred for readability, not speed.

Does the same problem exist elsewhere in Java?

Yes, anywhere a method takes a value rather than a supplier. Map.getOrDefault(key, compute()) computes the default every time, while computeIfAbsent takes a function. Objects.requireNonNullElse versus requireNonNullElseGet, and logging calls that build expensive messages, follow the same pattern.

How would a test catch this?

With a fake remote client that counts calls. A test that puts a value in the cache, performs a lookup and asserts that the remote call count is zero fails with orElse and passes with orElseGet. That test also documents the intent for the next developer.

7Conclusion

In this answer, we saw that Java evaluates method arguments before the call, so cache.get(key).orElse(loadFromRemote(key)) performs the remote call on every lookup and discards the result on cache hits, which is correct but slow and costly. orElseGet(() -> loadFromRemote(key)) passes a Supplier that runs only when the Optional is empty. The bug is common whenever the default is expensive or has side effects, static analysis can flag method calls inside orElse, and a loading cache such as Caffeine's get(key, loader) removes the pattern from caller code altogether.

What to say in the interviewAbout 90 seconds aloud

Open with

The bug is that orElse takes a value, not a function, and Java evaluates method arguments before calling the method. So in cache.get(key).orElse(loadFromRemote(key)), loadFromRemote runs first, on every single call, and only then does orElse look at the Optional.

Then, if they want more

When the cache has the config, orElse returns the cached one and the freshly loaded config is just thrown away. The result is always correct, which is why tests pass, but every lookup pays the network latency and sends a request to the remote service, so the cache does nothing for performance.

That is exactly the remote call the profiler shows. The fix is orElseGet(() -> loadFromRemote(key)). orElseGet takes a Supplier, so I am passing the instructions for loading rather than the loaded value, and Optional only calls it when it is empty. orElse is still fine for constants or values that already exist, like orElse(Config.DEFAULT).

This mistake is common whenever the default is expensive or has side effects, like a query, a remote call, allocating a collection or incrementing a counter. To prevent it, IntelliJ and Sonar have inspections that flag method calls inside orElse, and I would make sure that runs in the build.

I would also suggest a loading cache, for example Caffeine's get(key, loader), which loads and stores the value once per key and avoids duplicate loads under concurrency.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "A service is slow and a profile shows a remote call inside this line: Config c =...": https://scrivio-interview-library.netlify.app/java/optional/ca1cf824e6/