4

As discussed in this post, it is not suitable to use singleton in clustered environment (because of multiple singleton objects in different JVMs), this must be true for singletons created by Spring framework.

If that's correct, then we have to be a lot careful using Spring framework to use singleton classes. Can you please tell if this is correct understanding?

Community
  • 1
  • 1
Sandeep Jindal
  • 14,510
  • 18
  • 83
  • 121

1 Answers1

7

This is not necessarily the case.

It is a problem to use singletons across separate JVMs if they share meaningful state. For instance, a singleton that stored and issued incrementing IDs would be very dangerous if two separate instances existed on two separate application servers that were both part of the same application.

There is nothing inherent in Spring that makes this more or less tricky to deal with. Your Spring beans (likely services) should aim to maintain as little state as is practical as a matter of good practice. If they need to share state, then you will have to solve this problem just as you would with any other shared state.

A great many people use Spring in clustered environments and do not run into any problems relating to the above. I'm one of them!

DeejUK
  • 12,891
  • 19
  • 89
  • 169
  • This is an old answer but what about thread - safety . Lets say I have a critical section in service code guarded by a lock ( lock object is an instance field ) in service class. Multiple instances will have separate locks trying to use same resources resulting in contention. Am I correct? Any idea , how to handle that? – Sabir Khan Jun 12 '17 at 12:18