Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Doubt regarding singleton

 
sachin yadav
Ranch Hand
Posts: 156
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,

if i had a singleton class say x and two class a and b trying to get the instance of x at the same time, what will happen. Say a get the instance then will the object of x be shared in between a and b?
 
Hung Tang
Ranch Hand
Posts: 148
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, if you design a thread-safe Singleton.
 
sachin yadav
Ranch Hand
Posts: 156
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
So you mean to say that a single copy of instance will be shared between all the instantiating class objects. Right?
 
Frank Carver
Sheriff
Posts: 6920
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
So you mean to say that a single copy of instance will be shared between all the instantiating class objects. Right?

I think you may be getting confused about what a Singleton is and how it works.

When some code asks for a n instance of a Singleton it does not actually "instantiate" it. It just asks for one, usually by calling a static method somewhere. If an instance has already been created, that's the one it gets. Client code should never call "new" on a Singleton class, that's one of the key things which make it a Singleton.

Depending how the Singleton class is coded, the instance may be created when the Singleton's class is loaded into the JVM, or the instance may be created as a side effect the first time some client code asks for an instance. In practice, that doesn't really matter.

As a side note, please be aware that the Singleton design pattern is hugely over-used, and (in my opinion, and that of many people here) is almost never a good idea. Can you tell us any more about what you might be thinking of using a Singleton for?
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
So you mean to say that a single copy of instance will be shared between all the ...other... objects. Right?


I could buy this except that "shared" is not a well defined word here. I would say that many clients could reference the same Singleton. Just as many clients could reference the same non-singleton. Nothing new there.
 
sachin yadav
Ranch Hand
Posts: 156
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Frank Carver:
Can you tell us any more about what you might be thinking of using a Singleton for?


Thank you so much, i think i got my doubts cleared.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic