Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Java > singleton pattern

Reply
Thread Tools

singleton pattern

 
 
joe
Guest
Posts: n/a
 
      10-25-2004
Typical i write my singletons like this:

protected static MyClass singleton;
protected MyClass() { }
public static MyClass getInstance() {
if( singleton == null ) {
singleton = new MyClass();
}
return singleton;
}


However on more than once occasion I've come across this:
protected static MyClass singleton = new MyClass();
protected MyClass() {}
public static MyClass getInstance() {
return singleton;
}

Now for some reason the seconds way bothers me. I am not sure why ? Is
there something to this ? Or I am just being stupid ?

joe

 
Reply With Quote
 
 
 
 
Lasse Reichstein Nielsen
Guest
Posts: n/a
 
      10-25-2004
"joe" <(E-Mail Removed)> writes:

> Typical i write my singletons like this:


[lazy initialized singleton]

> However on more than once occasion I've come across this:


[singleton initialzed when class is loaded]

> Now for some reason the seconds way bothers me. I am not sure why ? Is
> there something to this ? Or I am just being stupid ?


The difference between the two methods is that the latter creates the
instance object when the class is loaded, and the former creates it
the first time it is requested.

The former has a small overhead each time the instance is requested,
because it tests whether it is null. The latter is potentially wastefull
if the instance is never requested.

So, if you know that you *will* request the instance (and what other
reason is there for loading a singleton class? then the latter is
*probably* fine. You can even make the instance field "final"

I also have an irrational preference for the lazily intialized
singleton, but I can't think of any singleton class I have ever used,
where I didn't request the singleton.

/L
--
Lasse Reichstein Nielsen - http://www.velocityreviews.com/forums/(E-Mail Removed)
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'
 
Reply With Quote
 
 
 
 
Babu Kalakrishnan
Guest
Posts: n/a
 
      10-25-2004
joe wrote:
> Typical i write my singletons like this:
>
> protected static MyClass singleton;
> protected MyClass() { }
> public static MyClass getInstance() {
> if( singleton == null ) {
> singleton = new MyClass();
> }
> return singleton;
> }
>
>
> However on more than once occasion I've come across this:
> protected static MyClass singleton = new MyClass();
> protected MyClass() {}
> public static MyClass getInstance() {
> return singleton;
> }
>
> Now for some reason the seconds way bothers me. I am not sure why ? Is
> there something to this ? Or I am just being stupid ?
>
>


The first way is not threadsafe - you might end up with more than one
instance of the "Singleton" unless your accessor is synchronized.

While the second example seems to create an instance even if the class
in question is not used, it isn't normally so. Most JVMs don't load the
class till some code makes a reference to it, and the instance will be
created only during classloading. (And in almost all cases that I have
encountered, the first access to a Singleton class is the getInstance()
call)


BK

 
Reply With Quote
 
Eric Sosman
Guest
Posts: n/a
 
      10-25-2004
joe wrote:
> Typical i write my singletons like this:
>
> protected static MyClass singleton;
> protected MyClass() { }
> public static MyClass getInstance() {
> if( singleton == null ) {
> singleton = new MyClass();
> }
> return singleton;
> }
>
> However on more than once occasion I've come across this:
> protected static MyClass singleton = new MyClass();
> protected MyClass() {}
> public static MyClass getInstance() {
> return singleton;
> }
>
> Now for some reason the seconds way bothers me. I am not sure why ? Is
> there something to this ? Or I am just being stupid ?


First, I think you want `private' rather than
`protected'. With the latter, it seems to me someone
could do:

class NoSingletonIsAnIsland extends MyClass {
public static MyClass makeAnotherOne() {
return new MyClass();
}
}

.... and proceed to make a million instances of your
"singleton" class.

As to your fundamental question, both approaches
have their place. If constructing the MyClass instance
is expensive and there's a reasonable chance you won't
ever need one, your "lazy initialization" style makes
sense. However, you'll need more bullet-proofing to
make it thread-safe; imagine what would happen if thread
T1 was busy in the MyClass constructor (it's assumed to
be expensive, so the constructor will take a while) and
T2 came along, found `singleton' still null, and started
constructing another one ... The second pattern avoids
the synchronization issues at the cost of *always* making
a MyClass instance, which would be a shame if it were
expensive and it turned out you didn't need one after all.

There's a discussion of both these patterns and of
some further variants in "Effective Java" by Bloch.

--
(E-Mail Removed)

 
Reply With Quote
 
Gordon Beaton
Guest
Posts: n/a
 
      10-25-2004
On Mon, 25 Oct 2004 18:52:39 +0200, Lasse Reichstein Nielsen wrote:
> [lazy initialized singleton]


> The former has a small overhead each time the instance is requested,
> because it tests whether it is null.


It also has a race condition that can only be solved by explicit
synchronization, missing from the example.

> [singleton initialzed when class is loaded]


> The latter is potentially wastefull if the instance is never
> requested.


Since the instance won't be created until the class itself is loaded
(which won't happen until it is needed at runtime), where is the
potential for waste?

The Java classloading mechanism already provides lazy initialization.
There is no need to implement it yourself in this case.

/gordon

--
[ do not email me copies of your followups ]
g o r d o n + n e w s @ b a l d e r 1 3 . s e
 
Reply With Quote
 
Doug Pardee
Guest
Posts: n/a
 
      10-26-2004
Babu Kalakrishnan <(E-Mail Removed)> wrote:
> Most JVMs don't load the class till some code makes a reference to
> it, and the instance will be created only during classloading.


Not "most"... *all*. This is required by section 12.4.1 of the Java 2
Language Specification.

Also, to be pedantic:
1) it's not the JVM that's involved, it's the ClassLoader, and
2) the singleton instance is NOT created during classloading; it is
created during class *initialization*.

The ClassLoader is permitted to load (and possibly link) the class
before it is needed, but the ClassLoader is *not* permitted to
initialize the class, thus running the "new" statement, until the
class is actually accessed.
 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Singleton methods without the singleton class Charles Oliver Nutter Ruby 4 03-22-2010 10:46 PM
Singleton object vs. enhancing singleton class Paul McMahon Ruby 3 06-09-2008 06:05 AM
Singleton Modules rather than Singleton Classes Trans Ruby 12 09-14-2007 06:45 AM
Singleton - Whether Cloneable overrides Singleton Proton Projects - Moin Java 4 03-27-2007 02:59 AM
Singleton classes and Singleton pattern Wilhelm Ruby 1 10-11-2006 01:08 PM



Advertisments