You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Core中为何该代码行必须置于synchronized()代码块中?

Why this.beanFactory = beanFactory Needs to Be in a Synchronized Block in Spring's refreshBeanFactory

Great question! Let's break down the key reasons this assignment is wrapped in synchronized(this.beanFactoryMonitor):

  • Guarantee thread visibility
    The beanFactory is an instance variable of the ApplicationContext. Without synchronization, when one thread writes to this variable, the change might not be immediately visible to other threads due to CPU caching or JVM optimizations. The synchronized block acts as a memory barrier: it flushes the write to main memory, ensuring all subsequent reads from other threads will see the updated beanFactory instance, not a stale or null reference.

  • Prevent race conditions with read operations
    Spring's getBeanFactory() method (used to access the bean factory from other code) also locks on the same beanFactoryMonitor for synchronized reads. Here's the relevant source code for context:

    @Override
    public final ConfigurableListableBeanFactory getBeanFactory() {
        synchronized (this.beanFactoryMonitor) {
            if (this.beanFactory == null) {
                throw new IllegalStateException("BeanFactory not initialized or already closed - " +
                        "call 'refresh' before accessing beans via the ApplicationContext");
            }
            return this.beanFactory;
        }
    }
    

    By wrapping the write in the same lock, we ensure no thread can read the beanFactory while it's being updated. This avoids scenarios where a thread might accidentally get a null or partially set-up bean factory if it calls getBeanFactory() mid-refresh.

  • Enforce a consistent happens-before relationship
    Even though we fully initialize the DefaultListableBeanFactory (via createBeanFactory(), customizeBeanFactory(), loadBeanDefinitions()) before the assignment, the JVM could theoretically reorder instructions without synchronization. The synchronized block ensures all prior initialization steps are completed and visible before the beanFactory reference is updated, eliminating any risk of exposing a partially initialized instance.

In short, this synchronization is critical for maintaining thread safety in environments where the ApplicationContext might be accessed concurrently during or after the refresh process.

内容的提问来源于stack exchange,提问作者Young Chan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 09:08:18