singleton pattern

J

joe

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
 
L

Lasse Reichstein Nielsen

joe said:
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
 
B

Babu Kalakrishnan

joe said:
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
 
E

Eric Sosman

joe said:
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.
 
G

Gordon Beaton

[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
 
D

Doug Pardee

Babu Kalakrishnan said:
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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,968
Messages
2,570,152
Members
46,698
Latest member
LydiaHalle

Latest Threads

Top