Skip to content

Avoid deadlock in getBeanNamesForType caching - #37517

Open
Pankraz76 wants to merge 1 commit into
spring-projects:mainfrom
Pankraz76:gh-37382-deadlock
Open

Pankraz76 wants to merge 1 commit into
spring-projects:mainfrom
Pankraz76:gh-37382-deadlock

Conversation

@Pankraz76

Copy link
Copy Markdown

Since gh-37382, the getBeanNamesForType cache uses ConcurrentReferenceHashMap#computeIfAbsent, so type matching runs while a cache segment lock is held. Type matching may instantiate a FactoryBean, which needs the singleton lock. A thread that holds the singleton lock and performs a type lookup can then deadlock with a thread that is matching types inside computeIfAbsent.

This PR goes back to the earlier get, compute outside any lock, then put arrangement, in a shared getCachedBeanNamesForType helper used by both the Class and the ResolvableType variants. ResolvableType cache keys and the reference-based cache from gh-37382 are kept. Concurrent first lookups may compute the same entry twice (last write wins, with an identical result), as before gh-37382.

BeanFactoryLockingTests#noDeadlockBetweenTypeLookupAndSingletonCreation reproduces the interleaving deterministically with latches and a predictBeanType hook. It uses 10s timeouts, so a regression fails the test instead of hanging the build.

Closes gh-37516

Since the getBeanNamesForType cache moved to computeIfAbsent on a
ConcurrentReferenceHashMap, type matching runs while holding the lock
of the cache segment for the requested type. With allowEagerInit,
type matching may instantiate FactoryBeans for type checks, which
requires the singleton lock. A thread that holds the singleton lock
(for example, while creating a lazy singleton) and performs a type
lookup for a type in the same segment then deadlocks with a thread
performing a type lookup that needs to create a FactoryBean.

This commit restores the previous get/compute/put arrangement,
computing the bean names outside of any cache lock, while retaining
ResolvableType cache keys and the reference-based cache.

See spring-projectsgh-37382

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015BqW8Vksjbb1UwwHvQiiB7
Signed-off-by: Vincent Potucek <vpotucek@me.com>
@Pankraz76

Copy link
Copy Markdown
Author

Hi @jhoeller, since this follows up on your gh-37382 change, I'd really appreciate your feedback when you have a moment.

The fix goes back to computing bean names outside the cache lock, but keeps the ResolvableType keys and the reference-based cache. I'm happy to adjust the approach or the test if you'd prefer something different, for example a different way to avoid holding the segment lock during type matching.

Thanks a lot for taking a look!

@cwiejack

Copy link
Copy Markdown

We hit this deadlock in production-like usage right after upgrading to Spring Boot 4.2.0 / Spring Framework 7.1.0 (GA).

Our application uses @ComponentScan(lazyInit = true), so most singletons are created on first request. With a few concurrent HTTP requests after startup, two Tomcat threads deadlock reliably. jstack reports "Found 1 deadlock":

  • thread A: DefaultSingletonBeanRegistry.getSingleton (holds singleton lock) → populateBean → findAutowireCandidates → getBeanNamesForType → waiting for the ConcurrentReferenceHashMap segment lock
  • thread B: LazyDependencyTargetSource.getTarget → getBeanNamesForType → computeIfAbsent (holds segment lock) → isTypeMatch → getTypeForFactoryBean → getSingletonFactoryBeanForTypeCheck → waiting for the singleton lock

It would be great to see this fixed in 7.1.1.

bdshadow added a commit to tolgee/tolgee-platform that referenced this pull request Nov 25, 2026
…#4088)

## Summary

Snyk reported critical, high and medium issues in the Docker image
(`/app/lib`). This PR bumps Spring Boot from 4.1.2 to 4.1.3. That brings
the fixed versions:

| Library | Before | After |
|---|---|---|
| Spring Framework (`spring-beans`, `spring-web`) | 7.0.10 | 7.0.11 |
| Spring Security (`spring-security-core`, `spring-security-web`) |
7.1.2 | 7.1.3 |
| Spring Boot (`spring-boot-actuator`, `spring-boot-security`) | 4.1.2 |
4.1.3 |

Fixed issues include:
- [CVE-2026-59273](https://spring.io/security/cve-2026-59273/): SpEL RCE
in Spring Security
- [CVE-2026-59374](https://spring.io/security/cve-2026-59374/) and
[CVE-2026-59389](https://spring.io/security/cve-2026-59389/): Spring
Framework
- [CVE-2026-59409](https://spring.io/security/cve-2026-59409/),
[CVE-2026-59413](https://spring.io/security/cve-2026-59413/) and
[CVE-2026-59414](https://www.herodevs.com/vulnerability-directory/cve-2026-59414):
actuator

The Netty pin also goes from 4.2.19 to 4.2.20.Final. Without that, our
pin would force Netty below the version in the new Boot BOM.

## Why not Spring Boot 4.2.0

Boot 4.2.0 also has these fixes. But it brings Spring Framework 7.1.0,
which has a deadlock between the `getBeanNamesForType` cache and the
singleton lock: spring-projects/spring-framework#37516. The fix PR
(spring-projects/spring-framework#37517) is not merged yet. In our
tests, the app context hung on startup: a `@Scheduled` task
(`TelemetryService.report`) and the context refresh deadlocked. We will
upgrade to 4.2 when Framework 7.1.1 is out.

## Testing

- All main and test sources compile.
- All `:security` tests pass, plus `AuthTest`, `HealthCheckTest`,
`PublicControllerTest` and `OpenApiTest`.


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

<!-- coderabbit-ai-generated:v1 -->

## Summary by CodeRabbit

* **Chores**
  * Updated Spring Boot and Netty to newer versions.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->
TolgeeMachine added a commit to tolgee/tolgee-platform that referenced this pull request Nov 25, 2026
## [3.246.2](v3.246.1...v3.246.2) (2026-11-25)

### Bug Fixes

* bump Spring Boot to 4.1.3 to patch Snyk-reported vulnerabilities ([#4088](#4088)) ([b458ad6](b458ad6)), closes [spring-projects/spring-framework#37517](spring-projects/spring-framework#37517)
@EliasZ

EliasZ commented Nov 25, 2026

Copy link
Copy Markdown

Another path to this deadlock with Spring Boot 4.2.0 / Spring Framework 7.1.0, during startup rather than under request load.

How it happens:

  • Spring Data JPA with spring.data.jpa.repositories.bootstrap-mode=deferred
  • a custom applicationEventMulticaster (SimpleApplicationEventMulticaster with a TaskExecutor), so ContextRefreshedEvent listeners run on a background thread
  • DeferredRepositoryInitializationListener then creates the repositories on that thread: it holds the singleton lock, then JpaRepositoryFactoryBean.setEntityPathResolver → getBeanNamesForType waits for the cache segment lock
  • at the same time main is in SpringApplication.callRunners → getBeanNamesForType → computeIfAbsent (holds the segment lock) → getSingletonFactoryBeanForTypeCheck waits for the singleton lock
  • SpringApplication.run never returns. Readiness stays OUT_OF_SERVICE and liveness UP, so nothing restarts the application, and the health endpoint keeps answering 503

Reproduced as follows:

  • on 7.1.0: 3 of 6 starts deadlocked (jstack: "Found one Java-level deadlock", main against the multicaster's executor thread)
  • the same application with only spring-beans replaced by v7.1.0 + this PR's commit: 15 of 15 starts fine
  • this PR's BeanFactoryLockingTests fails on plain v7.1.0 and passes with the change

Handling Spring's own lifecycle events on the publishing thread avoids it in the meantime.

@samuelhnrq

Copy link
Copy Markdown

One more path to this deadlock on Spring Boot 4.2.0 / Spring Framework 7.1.0 (Java 25), seen in @SpringBootTest integration tests that run with spring.main.lazy-initialization=true. jstack reports "Found one Java-level deadlock":

  • main: a test method triggers the creation of a lazy singleton. DefaultSingletonBeanRegistry.getSingleton (holds the singleton lock) → autowireConstructor → findAutowireCandidates → getBeanNamesForType → waits for the ConcurrentReferenceHashMap segment lock.
  • an @Async executor thread: the async method threw, so AsyncExecutionAspectSupport.handleError resolves the AsyncConfigurer beans for the first time (AbstractAsyncConfiguration → ObjectProvider.stream() → resolveMultipleBeans) → getBeanNamesForType → computeIfAbsent (holds the segment lock) → isTypeMatch → getTypeForFactoryBean → getSingletonFactoryBeanForTypeCheck → waits for the singleton lock.

It depends on timing: one run went through 179 test classes without it, the next one hung in the first minutes. The same suite does not hang on Spring Boot 4.1.3 / Spring Framework 7.0.11.

It would be great to have this fixed in 7.1.1.

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.

Deadlock between getBeanNamesForType cache and singleton lock

6 participants