Spring Singleton Thread Safety

后端 未结 4 556
后悔当初
后悔当初 2020-12-08 09:05

If I have a Java class defined below that is injected in my web application via dependency injection:

public AccountDao
{
   private NamedParameterJdbcTempla         


        
4条回答
  •  伪装坚强ぢ
    2020-12-08 09:32

    You could have asked for clarification on my initial answer. Spring does not synchronize access to a bean. If you have a bean in the default scope (singleton), there will only be a single object for that bean, and all concurrent requests will access that object, requiring that object to the thread safe.

    Most spring beans have no mutable state, and as such are trivially thread safe. Your bean has mutable state, so you need to ensure no thread sees a list of accounts the other thread is currently assembling.

    The easiest way to do that is to make the accounts field volatile. That assumes that you assign the new list to the field after having filled it (as you appear to be doing).

    private volatile List accounts;
    

提交回复
热议问题