Is this design of Spring singleton beans thread safe?

后端 未结 6 2159
[愿得一人]
[愿得一人] 2021-02-01 04:45

Consider the following Spring Service class. The spring scope defined is Singleton. The two service beans auto-wired as fields in the class below have similar structure - they t

6条回答
  •  挽巷
    挽巷 (楼主)
    2021-02-01 05:42

    Your code looks thread-safe. Spring doesn't guarantee thread-safety, when it says beans are singleton. If you make bean of singleton scope in spring, it simply mean that a single object instance per Spring IoC container is created. But still that singleton-scoped bean class may not be thread safe in itself, so its programmer's responsibility to make the code thread safe.

    In your code, documentGenerationService for instance is final. That guarantees that references cannot change, and also from new Java Memory model, instantiation is guaranteed. But @duffymo said, the objects being referred must be immutable as well.

    Rest all is good :)

提交回复
热议问题