• Post Reply Bookmark Topic Watch Topic
  • New Topic

Is this right way of creating singleton class?  RSS feed

 
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
public class ConnectionManager
{
Map cacheMap = null;
private ConnectionManager(){
cacheMap = new java.util.concurrent.ConcurrentHashMap();
}
public ConnectionManager getInstance(){
return ConnectionManagerHolder.instance;
}

private static class ConnectionManagerHolder{
private static final ConnectionManager instance = new ConnectionManager();
}

}

i believe that , there will be only one instance of connection manager, and i have cache map where it will hold cache data. Is this the right approach. Please advice?

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

Hm ... your example has nothing to do with the singleton.
So, the answer to your question (title) would be NO!

i believe that , there will be only one instance of connection manager, and i have cache map where it will hold cache data. Is this the right approach.

That's not true ... you'll end up with <N> instances.
So obviously this is the wrong approach.

Please advice?


Check the following link for how to create a singleton:
http://java.sun.com/developer/technicalArticles/Programming/singletons/


Regards,
Rok

PS: Don't reinvent the wheel.
 
Ranch Hand
Posts: 5575
Eclipse IDE Java Windows XP
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please use the code tag while you are posting your code. and Yes , your example class is not a singleton
 
Ranch Hand
Posts: 276
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Rok Štelcer wrote:Hm ... your example has nothing to do with the singleton.


Actually, it has a lot to do, just google Bill Pugh singleton!

Rok Štelcer wrote:That's not true ... you'll end up with <N> instances.


In rare cases, when multiple class loaders load the same class...
 
Lorand Komaromi
Ranch Hand
Posts: 276
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
karthikeyan siva, your getInstance should be static, I hope this is just a typo... Other than that, I didn't find any problems in your implementation...
 
Rok Štelcer
Ranch Hand
Posts: 101
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Actually, it has a lot to do, just google Bill Pugh singleton!

Thanks for the link ... didn't know it.
Anyhow, singleton is singleton and the code, which was/is shown is not a singleton ... sorry (missing static & private constructor).

You've assumed that it was just a typo, however what it the code was just copied from the editor? ;)
(rhetorical question)


Regards,
Rok
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!