Scrivio Interview library
ConceptFoundations6 min read · updated 12 November 2026

In Spring's caching annotations, what is the difference between the condition and unless attributes, and what does @Cacheable(sync = true) change? Give an example where using condition instead of unless is a bug.

condition is a SpEL expression evaluated before the method runs; when it is false the cache is neither read nor written for that call. unless is evaluated after the method runs and can only veto storing the result, which is why it is the one that can use #result. Writing condition = "#result != null" is a bug because there is no result yet when condition is evaluated. sync = true asks the cache provider to let only one thread compute the value for a given key while other threads for that key wait, within one JVM; it cannot be combined with unless, works with a single cache only, and depends on the provider supporting it.

Why this question is asked

The caching annotations look simple, but two of their attributes, condition and unless, sound almost the same and behave very differently. Mixing them up produces a method that either throws on every call or silently caches what we wanted to skip. sync = true is just as easy to misread as a distributed lock. Interviewers ask this question to check whether we know when each expression is evaluated, because timing is the whole difference. In this answer, we will recap where these attributes sit in a cached call, compare condition and unless, look at the bug that comes from using the wrong one, and then see what sync = true changes and where it stops.

1A Quick Recap: Where the Expressions Run

A call to a @Cacheable method goes through a proxy, a wrapper Spring generates around our bean, and its CacheInterceptor. The interceptor first decides whether to use the cache at all, then looks up the key, then on a miss calls our method, then decides whether to store the result. condition and unless are hooks into two of those steps. Both are written in SpEL, Spring's expression language, where #id refers to a parameter named id and #result refers to the method's return value.

Step throughA @Cacheable call and its two hooks
  1. condition true?
    YesLook in the cacheNoRun the method; no read, no write
  2. Entry found?
    YesReturn it; method skippedNoRun the method
  3. unless true?
    YesReturn result, do not storeNoStore the result, then return it

3 steps in order. Play them, or step through them one at a time.

condition runs before the method and gates everything; unless runs after and only gates the store.

2Condition Versus unless

condition answers the question: should this call use the cache at all? It is evaluated before the method, using only the arguments. When it is false, the interceptor skips both the lookup and the store, so the call behaves as if the annotation were not there. A typical use is to cache only some inputs, for example only short search terms.

Java
@Cacheable(cacheNames = "search", condition = "#term.length() <= 20")
public List<Hit> search(String term) { ... }
search("java"); // cached: condition true
search("a very long query string here"); // condition false: never read from or written to the cache
@Cacheable(cacheNames = "users", unless = "#result == null")
public User find(long id) { ... }
find(1); // user found: stored
find(999); // null: returned, but not stored, so the next call tries the database again

unless answers a different question: now that we have the result, should we refuse to store it? It is evaluated after the method runs, so it can look at #result. Notice that unless never prevents a cache read. If an entry already exists for the key, it is returned and unless is not even evaluated, because the method did not run.

3The Bug: Using condition to Inspect the Result

A common mistake is to reach for condition because it sounds like the general-purpose switch, and write the result check there.

Java
// Broken: there is no result yet when condition is evaluated
@Cacheable(cacheNames = "users", condition = "#result != null")
public User find(long id) { ... }
find(1); // fails: #result is not available before the method runs
// Fixed: veto the store after the method has run
@Cacheable(cacheNames = "users", unless = "#result == null")
public User find(long id) { ... }
find(1); // stored
find(999); // returns null, not stored

In current Spring versions, referencing #result in condition on @Cacheable makes the expression evaluation fail at runtime, with an exception saying the variable is not available (check your version for the exact class name). In a looser setup it could also be written as a check that never matches, which silently disables caching for every call. Either way, the fix is the same: anything that depends on the return value belongs in unless. Notice also that the logic flips: condition says when to cache, unless says when not to store.

4What sync = true Changes

Without sync, if 50 threads ask for the same missing key at the same moment, all 50 see a miss and all 50 run the method. For an expensive query, that is 50 identical database calls. With sync = true, the interceptor calls the provider's get(key, loader) method instead of a separate get and put, and the provider makes sure that only one thread runs the loader for that key while the others wait and then receive the same value.

Java
@Cacheable(cacheNames = "reports", key = "#day", sync = true)
public Report dailyReport(LocalDate day) { return expensiveQuery(day); }
// 50 threads call dailyReport(today) at once on a cold cache:
// without sync: expensiveQuery runs 50 times
// with sync: expensiveQuery runs 1 time, 49 threads wait and get the same Report

There is a catch: this protection is only within one JVM. With 30 instances, sync = true still allows up to 30 concurrent loads, one per instance. It also comes with restrictions: sync cannot be combined with unless, the annotation may name only one cache, and no other caching annotation may be combined on the same method. How well the waiting works depends on the provider: Caffeine and ConcurrentMapCache compute atomically per key, while for remote caches the locking happens in the client JVM. Check your provider's behaviour.

5Follow-up questions

Can condition and unless be used together?

Yes, and they combine naturally. condition decides whether the call takes part in caching at all, and for calls that do, unless can still refuse to store a particular result. For example, condition = "#region != 'TEST'" with unless = "#result.isEmpty()" caches real regions but never stores empty lists.

What does #result mean when the method returns Optional?

Spring unwraps Optional for caching, so #result refers to the value inside, or null for an empty Optional. That means unless = "#result == null" correctly skips storing empty Optionals, and the cache holds the plain object rather than the Optional wrapper.

Is sync = true a replacement for a distributed lock?

No. It coordinates threads inside one JVM through the provider. Across instances it gives no guarantee, so a hot key expiring on 30 instances can still cause 30 loads. If that is too many, we need refresh-ahead, stale-while-revalidate or a short distributed lease on top.

6Conclusion

In this answer, we saw that condition is evaluated before the method and switches caching off entirely for a call, while unless is evaluated after the method and only prevents the result from being stored, which is why only unless can use #result. Writing condition = "#result != null" is therefore a bug, and the fix is unless = "#result == null". We also saw that sync = true makes the provider load a missing key once per JVM while other threads wait, that it cannot be combined with unless or several caches, and that its behaviour depends on the provider.

What to say in the interviewAbout 90 seconds aloud

Open with

The difference is when they are evaluated. condition is a SpEL expression evaluated before the method runs, using only the arguments, and if it is false the cache is completely bypassed for that call: no lookup and no store. unless is evaluated after the method has run, so it can refer to #result, and it only vetoes storing the result; it never prevents a read of an existing entry.

Then, if they want more

So the classic bug is writing condition = "#result != null" to avoid caching nulls. At that point there is no result yet, so in current versions the expression fails at runtime because #result is not available. The correct version is unless = "#result == null". A good use of condition is something like caching only short search terms.

For sync = true, it changes how a miss is handled: instead of a separate get and put, Spring calls the provider's get with a loader, and the provider lets only one thread compute the value for that key while the others wait and receive it.

That prevents a stampede inside one JVM, but with many instances each one can still load once. It has restrictions: you cannot combine it with unless, you can only name one cache, and you cannot combine it with other caching annotations on the same method. And the exact locking depends on the provider.

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 "In Spring's caching annotations, what is the difference between the condition and unless...": https://scrivio-interview-library.netlify.app/databases/caching/f7e76249c1/