转载

spring getBean导致死锁问题

如果发生死锁,一般是这个方法导致,里面有个synchronized (this.singletonObjects)

org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(String, boolean)

/**
     * Return the (raw) singleton object registered under the given name.
     * <p>Checks already instantiated singletons and also allows for an early
     * reference to a currently created singleton (resolving a circular reference).
     * @param beanName the name of the bean to look for
     * @param allowEarlyReference whether early references should be created or not
     * @return the registered singleton object, or {@code null} if none found
     */
    @Nullable
    protected Object getSingleton(String beanName, boolean allowEarlyReference) {
        Object singletonObject = this.singletonObjects.get(beanName);
        if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {
            synchronized (this.singletonObjects) {
                singletonObject = this.earlySingletonObjects.get(beanName);
                if (singletonObject == null && allowEarlyReference) {
                    ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName);
                    if (singletonFactory != null) {
                        singletonObject = singletonFactory.getObject();
                        this.earlySingletonObjects.put(beanName, singletonObject);
                        this.singletonFactories.remove(beanName);
                    }
                }
            }
        }
        return singletonObject;
    }

出现这种情,一般都是代码引起的。如果你的代码中有用到 @PostConstruct 注解。表示在spring容器加载完毕后执行某个方法。重点检查这个方法,不能有线程阻塞操作,最好另起一个线程跑。

解决思路:保证spring容器完全加载完毕,然后在执行后续操作。后续操作尽可能另起一个线程执行。

原文  https://blog.csdn.net/thc1987/article/details/80898599
正文到此结束
Loading...