• Post Reply Bookmark Topic Watch Topic
  • New Topic

Singleton only creates 1 Instance or more ?  RSS feed

 
Prabhat Ranjan
Ranch Hand
Posts: 397
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I have query regarding Singleton. As i know that Singleton means only one instance per class and if any one creates more than 1 then it will return the same instance. Correct.

If we create say 5 instance as per our requirement means like a pool where if any one creates more than five instance then it will return any one of the instance from 5.

1) So can we call this implementation as Singleton Design patterns or not ?

2) I have implemented the code for the same and if i create 6th,7th or 8th instance its returns me the 5th instance always ! why for every run JVM may pickup.

please find the code :


here is the output:



please let me know you remarks/comments on the above problem.
 
Evan Caballero
Ranch Hand
Posts: 59
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
please edit your message putting your code around code tags ;)

Then, you should learn more about singletons. The code you have writen does not look like a singleton pattern. The first 5 "SinglePool" instances will be lost, because you initialize a new SinglePool() each time you call the getInstance method, and put it in the static variable singlePool.
 
Prabhat Ranjan
Ranch Hand
Posts: 397
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ok i have edited my code in code Button option.
 
Evan Caballero
Ranch Hand
Posts: 59
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Perhaps this code will help you a little bit :



Here is the resulted output :
 
Prabhat Ranjan
Ranch Hand
Posts: 397
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
yes correct which i was also thinking to take five instance of array !

private static final List<SinglePool> pool = new ArrayList<SinglePool>(5);

Good and one more thing still we can say its a Singleton Patterns !

Thanks Again for your Suggestion.

Prabhat
 
Evan Caballero
Ranch Hand
Posts: 59
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
by definition, a singleton can only instanciate one object, so, this is not a singleton.

you should read the java.util.concurrent API. Here you will find plenty of classes that should help you with these kind of pools.
 
Prabhat Ranjan
Ranch Hand
Posts: 397
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Evan !

java.util.concurrent is in jdk1.5 ! correct ?
 
Evan Caballero
Ranch Hand
Posts: 59
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
yep
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!