CodexBloom - Programming Q&A Platform

Java 17 - Difficulty with Lazy Initialization of Spring Beans in Multi-threaded Applications

πŸ‘€ Views: 1 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-06
spring multithreading lazy-initialization Java

I'm trying to configure I can't seem to get I'm working with issues with lazy initialization of Spring beans in a Java 17 application when accessed from multiple threads. I've defined a bean using `@Lazy` annotation to delay its creation until it's actually needed. However, I'm observing that when two threads try to access this bean simultaneously, one of them is throwing a `BeanCurrentlyInCreationException` due to the bean being in the process of initialization. Here’s a simplified version of my configuration: ```java @Configuration public class AppConfig { @Bean @Lazy public MyService myService() { return new MyService(); } } ``` And in my service class, I have: ```java @Service public class MyOtherService { @Autowired private MyService myService; public void performAction() { myService.doSomething(); } } ``` I’m launching multiple threads to invoke `performAction()`, and I see the following behavior in the logs: ``` org.springframework.beans.factory.BeanCurrentlyInCreationException: behavior creating bean with name 'myService': Requested bean is currently in creation: Is there an unresolvable circular reference? ``` I’ve tried several approaches, including using `@Scope` with `ConfigurableBeanFactory.SCOPE_PROTOTYPE` and adding synchronization around the bean access, but it just leads to performance bottlenecks. Additionally, I considered switching to using a `Supplier` and `@Bean` method, but I'm not sure if that's the best practice for this scenario. Is there a recommended way to handle this situation without sacrificing performance? Any insights would be greatly appreciated. This is for a service running on Windows 11. How would you solve this?