Skip to content

Avoid stale getBeanNamesForType cache entry for concurrent singleton creation - #37824

Open
egross wants to merge 1 commit into
spring-projects:mainfrom
egross:by-type-cache-publication-race
Open

egross wants to merge 1 commit into
spring-projects:mainfrom
egross:by-type-cache-publication-race

Conversation

@egross

@egross egross commented Dec 3, 2026

Copy link
Copy Markdown

Related: #37517 (same get/put change for the deadlock in gh-37516); this PR additionally fixes a stale cache entry.

With a frozen configuration, getBeanNamesForType computes the matching bean names and then caches them, while addSingleton evicts cached entries that the new singleton instance matches (added in 6.2.10 for gh-35239). Nothing orders the two:

  1. Thread A calls getBeanNamesForType(Impl.class). Bean impl is not created yet and its @Bean method declares Iface, so its predicted type does not match.
  2. Thread B creates and publishes impl. addSingleton's eviction finds nothing for Impl, since A has not cached yet.
  3. A caches the empty result.

A's own result is just the usual "lookup before creation" outcome. The problem is that it stays cached: every later lookup and autowiring by Impl (findAutowireCandidates -> beanNamesForTypeIncludingAncestors(..., allowEagerInit=true)) misses impl until the caches are cleared, failing with NoSuchBeanDefinitionException although the bean exists. registerSingleton has the same gap: its eviction runs inside addSingleton, before the manual singleton name is visible to lookups. Affects the Class-keyed cache since 6.2.10 and the ResolvableType-keyed cache since 7.1.0 (14a1cbb, gh-37382).

From the code, stock Spring can hit this (we have not observed it on unmodified Spring) when:

  • lazy singletons are first created at runtime while other threads do by-type lookups (getBeansOfType, ObjectProvider.stream(), prototype autowiring); none of these take the singleton lock.
  • background bootstrap (@Bean(bootstrap = BACKGROUND)) creates beans while a background bean or an ObjectProvider does a by-type lookup.

We found it while investigating an intermittent startup failure (roughly 1 in 200 startups) in a large application running a locally patched Spring with additional concurrent startup: a field injection by concrete type of a bean whose @Bean method declares the interface.

Fix: a generation counter, incremented on each eviction and cache clear. A lookup reads it before computing and, if it changed by the time the result is cached, removes its own entry (remove(key, value)). Either the lookup sees the new instance, or the lookup or the eviction removes the entry. registerSingleton evicts again after registering the name.

Like #37517, the lookup uses get/put instead of computeIfAbsent, so type matching (which may create beans) no longer runs under the cache's segment lock (gh-37516). This PR includes that change; happy to rebase onto #37517 instead.

Trade-offs: one AtomicLong increment per singleton publication. A lookup that overlaps any publication, matching or not, does not cache its result and computes again on the next call. That is never worse than no cache, but caching is less effective while many singletons are being published concurrently. Concurrent first lookups of one type may compute twice (as with #37517). Not covered (pre-existing): a FactoryBean whose object type only becomes known from its instance.

Tests: BeanNamesByTypeCacheRaceTests pauses the lookup thread in a predictBeanType callback for a bean registered after impl, publishes impl from the test thread, then lets the lookup finish. Covers Class and ResolvableType lookups for both caches, plus registerSingleton. All 5 fail on main (ced0465) and pass with the fix.

…creation

getBeanNamesForType computes its result before caching it. A singleton
that is published in between, and matches the requested type only by its
instance (for example via a factory method declaring a supertype), evicts
matching cache entries before the stale result is put, so the bean stays
invisible to by-type lookups until the caches are cleared. The same
applies to registerSingleton, where the manual singleton name becomes
visible to lookups only after the eviction.

A generation counter, incremented on every eviction and cache clear, lets
an overlapping lookup remove its own entry again, and registerSingleton
evicts once more after registering the name. The lookup no longer uses
computeIfAbsent, so that type matching (which may create beans) does not
run while holding a lock on the cache.

See spring-projectsgh-37516

Signed-off-by: Eric Gross <eric.gross@salesforce.com>
@spring-projects-issues spring-projects-issues added the status: waiting-for-triage An issue we've not yet triaged or decided on label Dec 3, 2026

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

status: waiting-for-triage An issue we've not yet triaged or decided on

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants