Repository navigation
Description
Mark Davies opened SPR-8471 and commented
A less significant version of this problem has already been raised under #10033 - a performance bottleneck affecting Wicket. However, the same issue causes a serious thread deadlock in our application, occasionally preventing application startup.
The basic issue seems to be that DefaultSingletonBeanRegistry takes a global synchronization lock when creating a singleton bean. Here is the code in that class:
public Object getSingleton(String beanName, ObjectFactory singletonFactory) {
Assert.notNull(beanName, "'beanName' must not be null");
synchronized (this.singletonObjects) {
Object singletonObject = this.singletonObjects.get(beanName);
if (singletonObject == null) {
... stuff ...
singletonObject = singletonFactory.getObject();
... stuff ...
}
The synchronized block (the same this.singletonObjects reference is used by all threads entering the method) means that Spring can only create singleton beans one at a time, regardless of their type (beanName). This clearly introduces a performance penalty if an application has a large number of singleton beans to construct, e.g. at startup.
That is not the issue affecting our code, though. We see a deadlock, caused by the following two sets of behaviour:
-
We have Spring-managed singleton beans which perform database access in their constructor (basically loading and caching configuration sets from the database). In order to do this they obtain database connections, which are pooled, with relatively small pool sizes. If a pooled connection is not available, the calling thread blocks and waits until one becomes free. This is usually not a problem since queries are small and rapid, so pool wait times are low, and the maximum pool size is sufficient to work the databasea at full capacity anyway.
-
We also have non-Spring code doing database access. Such code obtains a database connection from the same pool, purely for the lifetime of running a query and processing a result set, so again very quick for almost cases in our system. But sometimes, whilst processing the result set, we need to use a Spring-managed bean, which may have singleton scope.
You now have a deadlock - thread number one is trying to get a Spring-managed singleton bean, which is waiting for a JDBC connection in its constructor; thread number two is running database code which has the JDBC connection and is waiting to create a Spring-managed singleton of a completely different type. Both thread own the resource needed by the other, so will wait forever. (OK, if the database pool size is two or higher you need two or more threads in the second state, but this has happened to us in customer environments, in production).
Obviously our application code is almost certainly less than ideal in how we use Spring, but it seems to me that we ought to be able to use Spring-managed beans which do database access in the manner I've described, without encountering unpleasant deadlocks such as this. Note that the problem is actually much more general than this particular example of database connections: if your singleton beans require any kind of global monitor, which is also used outside of the context of Spring, you have a deadlock condition.
Both the originally-reported performance problem, and this deadlock, could be solved by a simple improvement to DefaultSingletonBeanRegistry. The getSingleton() method should not synchronize on a global monitor, but instead a monitor specific to the beanName you are instantiating. This is the correct level at which to lock - what you are trying to do is prevent a bean of a certain type being created more than once, but allowing two beans of different types to construct at the same time is perfectly reasonable. Of course you have to synchronize access to the underlying collections with a global lock, but the construction of the singleton bean does not need to be protected with the same global monitor. For instance I believe this kind of thing would do it:
public Object getSingleton(String beanName, ObjectFactory singletonFactory) {
Object bean;
Object perBeanMonitor;
synchronized (GLOBAL_MONITOR) {
perBeanMonitor = getPerBeanMonitor(beanName);
}
synchronized (perBeanMonitor) {
synchronized (GLOBAL_MONITOR) {
bean = getBeanFromRegistry(beanName);
}
if (bean==null) {
Object bean = doConstructBean(beanName, singletonFactory);
synchronized (GLOBAL_MONITOR) {
addToRegistry(beanName, bean);
}
}
}
return bean;
}
It would be extremely helpful if this approach could be implemented in this core part of the Spring framework. We rely on singleton construction to be performant and thread-safe; the fact that DefaultSingletonBeanRegistry behaves as it currently does is causing us serious production problems at client sites, and, whilst we can modify our application code to work around the issue, I do see this as a fundamental flaw in Spring - would be nice to get a quick fix please.
Affects: 2.5.6
Attachments:
- test-case.zip (3.09 kB)
Issue Links:
- Deadlock during application context creation [SPR-8785] #13428 Deadlock during application context creation ("is duplicated by")
- A Java Thread deadlock has occured [SPR-9837] #14470 A Java Thread deadlock has occured ("is duplicated by")
- Deadlock on the beanDefinitionMap and singletonObjects [SPR-9199] #13837 Deadlock on the beanDefinitionMap and singletonObjects ("is duplicated by")
- Deadlock between DefaultListableBeanFactory and DefaultSingletonBeanRegistry, perhaps due to lazily-instantiated aspect [SPR-7718] #12374 Deadlock between DefaultListableBeanFactory and DefaultSingletonBeanRegistry, perhaps due to lazily-instantiated aspect
- Non-singleton beans performance issue [SPR-9819] #14452 Non-singleton beans performance issue
- Deadlock in DefaultListableBeanFactory/DefaultSingletonBeanRegistry [SPR-10020] #14654 Deadlock in DefaultListableBeanFactory/DefaultSingletonBeanRegistry
- AbstractApplicationEventMulticaster#getApplicationListeners() should have double check for 'this.retrieverCache.get(cacheKey)' within synchronized block [SPR-10351] #14985 AbstractApplicationEventMulticaster#getApplicationListeners() should have double check for 'this.retrieverCache.get(cacheKey)' within synchronized block
Referenced from: commits dd68fec, 52124fa
19 votes, 26 watchers
Activity
spring-projects-issues commentedon Aug 10, 2011
ken lu commented
We have the similiar issue when we are using Spring JMS MessageListener to specify <property name="concurrentConsumers" value="10"/>
When Spring reads the context file, it starts 10 threads for the MessageListener. This creates a deadlock immediately when these threads get to the singleton Service or DAO.
The problem is the Service and DAO singleton should not be instanced by these thread.
The work around is to specify the MessageListener as lazy-init="true". Make sure all the singleton bean was created, then start the MessageListener.
Really hope Spring framework should sort this type of multi-threaded issue in a better way!
spring-projects-issues commentedon Oct 18, 2011
Jean-Pierre Bergamin commented
Maybe the issue #13428 is related.
spring-projects-issues commentedon Feb 29, 2012
John Cotter commented
This appears to be root cause of #12374 and OSGI-816 also. DefaultSingletonBeanRegistry could be refined so as not to hold a global lock on all singletons. As it is now, a second thread calling into DefaultSingletonBeanRegistry originating from call to DefaultListableBeanFactory can yield a deadlock. There is a wide array of use cases where this can occur.
spring-projects-issues commentedon Feb 29, 2012
John Cotter commented
Similar deadlock pattern involving DefaultSingletonBeanRegistry and DefaultListableBeanFactory observed with Spring 3.0.5.
spring-projects-issues commentedon Mar 1, 2012
Chris Beams commented
Linking as possibly related to #12374 per John's comment.
spring-projects-issues commentedon Mar 2, 2012
Piotr Bzdyl commented
I encountered a similar issue but it involved:
Deadlock report:
spring-projects-issues commentedon Mar 2, 2012
Piotr Bzdyl commented
I forgot to mention the deadlock occurred in 3.0.5.RELEASE.
spring-projects-issues commentedon Mar 12, 2012
Alex Rau commented
Same here with 3.1.0.RELEASE
spring-projects-issues commentedon Apr 26, 2012
Nicholas DiPiazza commented
This test case reproduces the issue.
spring-projects-issues commentedon May 15, 2012
Chris Beams commented
Thanks, Nicholas.
spring-projects-issues commentedon Nov 25, 2012
Juergen Hoeller commented
Note that along with the changes for #14452, several locking improvements made it into Spring Framework 3.2, including changes that avoid the deadlock potential outlined in the comments on this issue.
The deadlock-related changes have also been backported to Spring Framework 3.1.4.
Juergen
spring-projects-issues commentedon May 10, 2014
Hendy Irawan commented
I'm still getting this issue using 3.2.8.RELEASE :
spring-projects-issues commentedon May 10, 2014
Hendy Irawan commented
Blocks soluvas/soluvas-framework#66
spring-projects-issues commentedon Aug 13, 2014
Yvonnick Esnault commented
Hi,
This issue is not resolved (version 3.2.5 here)
spring-projects-issues commentedon Aug 13, 2014
Juergen Hoeller commented
Henry, Yvonnick,
Could you please clarify: Are we talking about thread contention here? Specifically, it doesn't seem like you're running into a deadlock but rather 'just' into wait times for a lock?
Juergen
1 remaining item
spring-projects-issues commentedon Aug 13, 2014
Juergen Hoeller commented
Hmm that seems to be a deadlock between Spring's singleton lock in the bean factory and some related lock behind a CXF FactoryBean... I'm afraid it's no good idea to wrap Spring bean lookup calls in a custom lock there in CXF, when CXF is currently within a Spring-driven bean creation attempt itself!
Juergen
spring-projects-issues commentedon Aug 13, 2014
Yvonnick Esnault commented
Some information from the CXF mailing list here http://mail-archives.apache.org/mod_mbox/cxf-users/201311.mbox/%[email protected]%3E
spring-projects-issues commentedon Aug 13, 2014
Juergen Hoeller commented
That sounds like they'll relax their custom lock in CXF which is definitely worthwhile.
I'm afraid we can't relax the singleton lock on our side, otherwise we'd immediately expose ourselves to a deadlock potential during the creation of lazy singletons with dependencies on other lazy singletons...
So I wonder: What specifically could we do on our side still, while keeping our factory-wide singleton lock?
Juergen
spring-projects-issues commentedon Sep 1, 2014
Juergen Hoeller commented
I'll keep this marked as resolved for 3.2 then, since I don't see any further changes that we could make without sacrificing our singleton guarantees...
Juergen
JasonMacKeigan commentedon Nov 27, 2019
This is still an issue in 2019.
inad9300 commentedon Jul 2, 2020
I've encountered the same issue with Spring Boot 2.3.1.RELEASE / Spring 5.2.7.RELEASE...
CODESTHN commentedon Aug 31, 2020
@jhoeller -- I have encountered same issue with Spring release 5.2.1. Please suggest what to do to. Also, please reopen this issue if possible. Thanks
jhoeller commentedon Aug 31, 2020
@CODESTHN Are you seeing specific thread contention for
getBeansOfTypethere, while some other thread is creating singleton beans? Is this a startup problem or happening later on for short-lived bean creation attempts? In any case, please create a separate GitHub issue specific to your scenario, we can try to look at it for 5.3 then.jhoeller commentedon Aug 31, 2020
Reviewing the recent stacktraces above, we seem to have a specific case about
DefaultSingletonBeanRegistry.getSingleton(beanName, false)here, as called fromisSingletonandisTypeMatchchecks inAbstractBeanFactory. WhenisSingletonCurrentlyInCreationreturnstrue, we're trying to enter the global lock for an early singleton exposure check... even if we're not allowed to create early references, so only able to check for an existing early reference. By turningearlySingletonObjectsinto aConcurrentHashMapand separating that early reference existence check from the creation of early references (which needs to happen within the global lock), we could potentially address a whole range of issues here, including this latest report, for lookup attempts in concurrent singleton creation scenarios.I'll create a GitHub issue myself to that effect, even for 5.2.9 since such a change seems straightforward enough.