简体   繁体   中英

Is Spring's @Lazy initialization thread-safe?

Hopefully a simple question to answer. I couldn't find any absolute clear answer on this. Can anyone please help with a credible source.

I'm going by the general perception that lazy loading is dangerous in a multithreaded application without using a proper synchronized block. I'm wondering if this is applicable for Spring or not.

Thanks.

I dont know anywhere Spring claims for safe publication of the beans managed by IoC container.

However, quick glance through the bean factory/application context code detects that there are a lot of crucial places guarded by synchronization (eg registering/unregistering bean definition, post-processing phase etc). See many of the methods in DefaultSingletonBeanRegistry has synchronized blocks.

About lazy initialized beans - i see that inside of DefaultSingletonBeanRegistry, construction is guarded by a lock around singletonObjects instance variable. in addition, singletonObjects itself is a concurrent hash map.

It uses double-checked locking (org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton()), so the bean is safely published.

In addition regarding thread safety,i remember spring had bugs previously in initial release and is improved with versions , And note that :

1.singleton beans (lazy and non-lazy) are always fully instantiated (including init methods) and safely published. therefore their construction is thread-safe - if another thread does see this bean, it would never see a half-initialized singleton with default values for some fields

2.prototype beans construction is not thread-safe, but usually prototype beans are not shared between threads, and if they have to be - you are on your own to make sure you publish them to other threads safely this behavior is intended by the framework

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM