Issue
I am learning Spring, and I know that bean will be by default singleton in one application context.But what if we deploy the applications in distributed system? What will be the practical way to achieve singleton since every time a request comes in, it may be routed to a different machines with a different application context?
I have read Singleton in Cluster environment but the answer is about cache.
I guess we can do something like putting the singleton into a central place(like memcached) , and every time we need this bean and serialize and deserialize it from IO, Does this work? But, in my opinion, this will be cost a lot since some object is very "expensive" to transfer.
Thank you!
Solution
Either your singleton is stateless: then you just re-create the same thing in each node, with no communication between nodes needed;
or your singleton is stateful: then you need to distribute its state. This is where
memcached
or any other of a slew of available distributed caches must be applied. You will still be re-creating the singleton itself in each node independently, but you'll make its internal state reside in the distributed cache.
Answered By - Marko Topolnik
Answer Checked By - Pedro (JavaFixing Volunteer)