Results 1 to 3 of 3
Thread: Singleton
- 09-19-2010, 11:40 AM #1
Member
- Join Date
- Jan 2010
- Posts
- 8
- Rep Power
- 0
Singleton
i founr this implementation :
public class Singleton
{
// Private constructor suppresses generation of a (public) default constructor
private Singleton() {}
/**
* SingletonHolder is loaded on the first execution of Singleton.getInstance()
* or the first access to SingletonHolder.INSTANCE, not before.
*/
private static class SingletonHolder
{
private final static Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance()
{
return SingletonHolder.INSTANCE;
}
}
i cant understand how only one Instance of the class is created?
if we call SingletonHolder twice it seems that there will be 2 object created.
what am i missing here?
- 09-19-2010, 12:17 PM #2
- Join Date
- Sep 2008
- Location
- Voorschoten, the Netherlands
- Posts
- 11,385
- Blog Entries
- 7
- Rep Power
- 17
I find that quite an obscure way to implement a singleton; I normally do it like this:
There are a few problems with this class: if several class loaders are used several 'singletons' are created. If the Singleton class isn't used but loaded the singleton is still eagerly created.Java Code:public class Singleton { private Singleton instance= new Singleton(); public Singleton getInstance() { return instance; } ... private Singleton() { ... } }
kind regard,
Jos
- 09-20-2010, 10:15 AM #3
Moderator
- Join Date
- Apr 2009
- Posts
- 10,438
- Rep Power
- 16
All the first version is doing is avoiding the eager loading.
However, from my point of view, there's rarely if ever anything else in a Singleton that would result in it being loaded prior to a call to getInstance(), so I don't really see the value in the SingletonHolder style.
Now someone'll come along and point out something...:)
Similar Threads
-
[SOLVED] Hacking Singleton- Multiple instance of a Singleton class
By piyu.sha in forum New To JavaReplies: 2Last Post: 10-06-2008, 09:06 PM -
singleton object ...
By haiforhussain in forum Advanced JavaReplies: 8Last Post: 06-23-2008, 06:43 AM -
Whether to make Bean Singleton or non Singleton (prototype)
By Java Tip in forum Java TipReplies: 0Last Post: 03-29-2008, 12:41 PM -
Whether to make Bean Singleton or non Singleton (prototype)
By JavaBean in forum Java TipReplies: 0Last Post: 09-26-2007, 08:32 PM -
singleton pattern
By Peter in forum Advanced JavaReplies: 1Last Post: 07-09-2007, 04:45 AM


LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks