Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

How to ensure creation of exactly n number of instances of a Class ?  RSS feed

 
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How can we ensure exactly n ( a perticular ) of instances are only created of a perticular class ?

 
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Check out class Multiton in this thread. If you want a little more control over a specific instance to return (e.g. use only idle instances, whatever idle means for your objects) you should check out how to use a pool. Perhaps you can use Apache Commons Pool as a base.
 
Jayati Das
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you Rob for your help, Multiton was what I was looking for .Multiple (n)singletons.
 
Rob Spoor
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're welcome
 
Bartender
Posts: 10575
66
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jayati Das wrote:Thank you Rob for your help, Multiton was what I was looking for .Multiple (n)singletons.

Just FYI, another use of instance control is for LRU (least-recently-used) caches, which are somewhat akin to pools.

You can find one method for this in LinkedHashMap.removeEldestEntry().

Winston
 
Rob Spoor
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It would require you to extend LinkedHashMap though, since the method is protected.
 
Winston Gutkowski
Bartender
Posts: 10575
66
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Rob Spoor wrote:It would require you to extend LinkedHashMap though, since the method is protected.

Indeed, but it works beautifully.

Winston
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!