2

I am trying to understand the singleton design pattern. It says that only one object is created in the jvm. But I want to understand how does this work in cloud based environment. Also how many objects are created?

suish
  • 3,039
  • 1
  • 12
  • 33
manjosh
  • 263
  • 2
  • 15

2 Answers2

4

A singleton object is created on in the context of a single Java process, running in a single JVM instance. It has nothing to do with whether the process and the JVM runs on a local physical machine, or in a container, or a virtual machine in the cloud.

Also, even on a the same machine, multiple instances of the same process will each produce their own instance of a singleton object. There is nothing magical about the singletons that would cause separate processes to share a singleton instance.

The most typical method for creating singleton objects is to have a static member of a type reference an instance of an object. Since types are only constructed once by the JVM, that implies a single unique reference to the respective object (though there is nothing preventing multiple instances of that object from being created in the general sense).

Going back to your original question - assuming that by "cloud based environment" you meant a distributed application deployed on multiple machines, connected over a network - then again, by default, each machine, running the process would get it's own separate instance of the "singleton", unless there is some other distributed data structure that underlies the "singletons" to make them share state etc.

Incidentally - you didn't ask, but: What is so bad about singletons?

Mike Dinescu
  • 48,812
  • 10
  • 104
  • 136
1

Applying the singleton pattern in the Java world almost automatically means creating singleton objects of a given class. Objects of classes live in the context of the JVM, the "single" instance is per VM process.

It can in fact get worse than that, as multiple class loaders withing a single JVM can lead to multiple "singletons" within the sam JVM (for example, in a JEE application where class loaders are isolated).

But singleton being a pattern, it can in an abstract way be applied to an application or system as a whole. Of course the technology or component type may have to change.

Distributed systems can also have a concept of "singleton component". Ignite cluster singleton services is a good example. This of course redefines the scope of the singleton object, but it's almost nothing new since we've always used single instances of certain types (such as a single database) in a multi-application system anyway.

ernest_k
  • 39,584
  • 5
  • 45
  • 86
  • 1
    Glad that you added the part about "singleton" components and gave an example. I was just about to write my own answer in that regard ;-) – GhostCat Jul 13 '18 at 07:26