Quick revision
The short answer
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.
What to remember
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.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
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.
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.
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.
| Default expression | Use | Why |
|---|---|---|
"unknown", 0, Config.DEFAULT | orElse | already a value; nothing to evaluate |
new ArrayList<>() | orElseGet | allocates on every call otherwise |
repository.find(...), remote call | orElseGet | expensive; must run only on a miss |
| anything with side effects | orElseGet | the effect would happen on every call |
| throwing when absent | orElseThrow(supplier) | exception built only when needed |
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.
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.
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.
- Official documentation
- java.util.stream, package documentation, java.util.function, package documentation
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/