Search code examples
springsingletonapplicationcontext

Spring Singleton and concurrent access


My question is : let's assume that i have a spring bean : a DAO one (it's a singleton of course)

So, when we have lot of users who want to use this bean at the same time : what happens?

or,

for every user, spring instantiate a DAO bean for him?

==> we have a singleton by application Context : did spring create a context for every user?


Solution

  • (it's a singleton of course)

    Then it's a singleton. The ApplicationContext will only create one instance and pass that same instance around wherever it's requested.

    for every user, spring [instantiate] a DAO bean for him?

    No, it will retrieve and give them the same DAO instance.

    ==> we have a singleton by application Context : did spring create a context for every user?

    I'm not exactly sure what you mean for every user. A Java application has no knowledge of users. If you mean in the context of a multithreaded application, it's still irrelevant. The injected DAO bean will still be that single instance.

    As stated in the comments, it's your responsibility to handle the state of your DAO, if it's mutable, handle concurrent access. Handle transactions (possibly with @Transactional) with the datasource.