spring-framework icon indicating copy to clipboard operation
spring-framework copied to clipboard

Deadlock in @PostConstruct block

Open uhushcha opened this issue 2 years ago • 0 comments

Found it in 5.3.22

In PostConstruct i make a call for subscribe to event ( in external system)

I use webclient and tracing ( spring cloud sleuth) I got deadlock in DefaultSingletonBeanRegistry.getSingleton method. When webclient try to make a call. By default weblient use reactor.netty.http.brave.TracingHttpClientDecorator. After this application try to get and create singleton bean org.springframework.cloud.sleuth.autoconfig.brave.BraveSamplerConfiguration$RefreshScopedSamplerConfiguration and try to get "synchronized (this.singletonObjects)" in DefaultSingletonBeanRegistry.getSingleton

uhushcha avatar Aug 08 '22 13:08 uhushcha

You shouldn't do stuff like this in a @PostConstruct method, bean construction hasn't completely finished at that point and using other beans that might themselves not be fully initialized can cause these problems. Wait for the context to be ready to use and then do your call. If you're using Spring Boot, you can use an event listener:

@EventListener(ApplicationReadyEvent.class)
public void ready() {
  // webClient call here
}

Or have your bean implement CommandLineRunner, which will have it be invoked automatically once the context is ready to use.

kzander91 avatar Aug 11 '22 15:08 kzander91

It's indeed not a good idea. You could use SmartInitializationSingleton instead as afterSingletonInstantied provides a better callback for things like.

I am going to close this as a duplicate of https://github.com/spring-projects/spring-framework/issues/20904

snicoll avatar Aug 19 '22 15:08 snicoll