Singleton Question

D

Dave Monroe

Can somebody point me to a spec for singleton implementation?

I'm working with an application that has a couple of singletons and
obviously the member variables are kept separate in the threads that
use the singleton, but I can't find any documentation that explains
the rules.

TIA

Dave Monroe
 
C

Chris Smith

Dave said:
Can somebody point me to a spec for singleton implementation?

Singleton is a pattern, not a specification. There is a description of
the general pattern on page 127 of GoF. In general, Java
implementations use the static initialization time feature to avoid
overhead when retrieving an object, as such:

public class MySingletonClass
{
private static MySingletonClass instance = new MySingletonClass();

public static MySingletonClass getInstance()
{
return instance;
}

private MySingletonClass() { }

...
}

Unlike similar-looking code in other languages, this will *not* create
an instance of MySingletonClass until the first time getInstance is
called (or the first time MySingletonClass is loaded directly from a
classloader with an explicit request to initialize it). Essentially,
lazy initialization is provided for you as a feature.
I'm working with an application that has a couple of singletons and
obviously the member variables are kept separate in the threads that
use the singleton, but I can't find any documentation that explains
the rules.

What you're describing doesn't really sound like a Singleton at all.
Singletons are shared objects, and are intended that way. They
generally have little or no state at all, and thread-local state is
certainly not a part of the pattern.

--
www.designacourse.com
The Easiest Way to Train Anyone... Anywhere.

Chris Smith - Lead Software Developer/Technical Trainer
MindIQ Corporation
 
G

Guest

Chris said:
Singleton is a pattern, not a specification. There is a description of
the general pattern on page 127 of GoF. In general, Java
implementations use the static initialization time feature to avoid
overhead when retrieving an object, as such:

public class MySingletonClass
{
private static MySingletonClass instance = new MySingletonClass();

public static MySingletonClass getInstance()
{
return instance;
}

private MySingletonClass() { }

...
}

My normal way in Singleton handling is instead:

public class MySingletonClass
{
public static final MySingletonClass instance = new MySingletonClass();

private MySingletonClass() { }

...
}

Which are pros and cons of my vs your way ?

- Dario
 
C

Chris Smith

Dario said:
Which are pros and cons of my vs your way ?

Not a lot. I guess I write a getXXX method because it more closely
resembles the way singleton is often implemented in other languages.
Either is equally valid, though.

--
www.designacourse.com
The Easiest Way to Train Anyone... Anywhere.

Chris Smith - Lead Software Developer/Technical Trainer
MindIQ Corporation
 
L

Lance Lamboy

My normal way in Singleton handling is instead:

public class MySingletonClass
{
public static final MySingletonClass instance = new
MySingletonClass();

private MySingletonClass() { }

...
}
}
Which are pros and cons of my vs your way ?

I would recommend hiding accessing to the singleton through a public
method. That way you preserve flexibility. You could update the
previously mentioned MySingletonClass to the below code without anyone
else having to change their code.

public class MySingletonClass // used to be a singleton but changed for
operational reasons
{
private static MySingletonClass a = new MySingletonClass(); private
static MySingletonClass b = new MySingletonClass();

public static MySingletonClass getInstance() {
if ( delta ( ) return a ; )
return ( b ) ;
}
}
private static boolean delta ( ) { ... }

private MySingletonClass() { }

...
}
}
 
G

Gorf

Chris Smith said:
Not a lot. I guess I write a getXXX method because it more closely
resembles the way singleton is often implemented in other languages.
Either is equally valid, though.

I do it a slightly different way, lazy instantiation...

public class MySingletonClass {

private static MySingletonClass instance;

public static MySingletonClass getInstance() {
if (instance == null)
instance = new MySingletonClass();
return instance;
}

private MySingletonClass() { }

...
}

It's got an if-statement in there, but for some reason, I like it this way
:)
 
K

Keith James

[...]

Gorf> I do it a slightly different way, lazy instantiation...

Gorf> public class MySingletonClass {

Gorf> private static MySingletonClass instance;

Gorf> public static MySingletonClass getInstance() {
Gorf> if (instance == null)
Gorf> instance = new MySingletonClass();
Gorf> return instance;
Gorf> }

Gorf> private MySingletonClass() { }

Gorf> ...
Gorf> }

Gorf> It's got an if-statement in there, but for some reason,
Gorf> I like it this way :)

Lazy, but not threadsafe. You're much better off with Chris'
suggestion which is both.
 
G

Guest

Lance said:
I would recommend hiding accessing to the singleton through a public
method. That way you preserve flexibility. You could update the
previously mentioned MySingletonClass to the below code without anyone
else having to change their code.

Ok. Thanks.

- Dario
 
C

Chris Smith

Gorf said:
I do it a slightly different way, lazy instantiation...

Here's probably more than you want to know...

The reason is rather subtle, but both of our pieces of code do lazy
instantiation. If I write:

public class MySingletonClass
{
private static MySingletonClass instance = new MySingletonClass();
...
}

That new object is created at class initialization time. In Java, class
initialization happens directly prior to the first access to the class,
and *not* at the beginning of the application.

Java is primarily designed that way because there's no way for the JVM
to know all the classes that will be used when the application first
begins -- as opposed to many other languages where an explicit link step
provides this information. In this case, though, we can take advantage
of this fact (which is specified, and therefore guaranteed) to delay
initialization of a singleton instance.

The primary advantage of the code as I wrote it above is that it is
implicitly thread-safe to retrieve the singleton instance. You could
provide this thread-safety explicitly in your version by synchronizing
the getInstance method, but there are several reasons it's at least
marginally better to go with class initialization:

1. The thread synchronization for class initialization is going to
happen anyway (to set your instance field to null, for example),
so you'd just be introducing redundant synchronization.

2. Synchronization can be done better by the JVM. It knows that
class initialization can only happen once, so it can (and almost
certainly does) actually mutate the code so that there is zero
cost for the synchronization after class initialization is
complete.

You may not be working in a multithreaded environment (although that's
hard to imagine in Java), or you might not be concerned about
performance, but when the better and faster technique is also easier to
read and write, it makes a good default to use that technique.

--
www.designacourse.com
The Easiest Way to Train Anyone... Anywhere.

Chris Smith - Lead Software Developer/Technical Trainer
MindIQ Corporation
 
G

GaryM

Lazy, but not threadsafe. You're much better off with Chris'
suggestion which is both.

Not to go off on a tangent, but I was reading about double check
locks recently. Does this make his example thread safe:

if (instance == null) {
synchronized(this) {
if(instance == null)
instance = new MySingletonClass();

}
}
return instance;
 
P

Phillip Lord

GaryM> Not to go off on a tangent, but I was reading about double
GaryM> check locks recently. Does this make his example thread safe:

GaryM> if (instance == null) {
GaryM> synchronized(this) {
GaryM> if(instance == null)
GaryM> instance = new
GaryM> MySingletonClass();

GaryM> }
GaryM> }
GaryM> return instance;

I don't think that you can use a "this" reference here. The factory
method is in the static context, so there is not this.


All of this is unnecessary. Without any of this, still the instance
will only be created when the class is loaded. This will happen the
first times it's referenced in a static context, which you have to do
to get to the instance.

So the class loader already provides you with lazy instantiation, and
more over provides you with synchronisation. There is just no point to
what you are doing.

Cheers

Phil
 
G

Guest

GaryM said:
Not to go off on a tangent, but I was reading about double check
locks recently. Does this make his example thread safe:

if (instance == null) {
synchronized(this) {
if(instance == null)
instance = new MySingletonClass();

}
}
return instance;

There is not 'this' in a static method.
 
C

Chris Smith

GaryM said:
Not to go off on a tangent, but I was reading about double check
locks recently. Does this make his example thread safe:

if (instance == null) {
synchronized(this) {
if(instance == null)
instance = new MySingletonClass();

}
}
return instance;

No. Never do that. It was an interesting idea, and got spread around
by a lot of people that appreciated how clever it is. We're now in the
stage of growing realization that double-checked locking is inherently
broken in most cases.

Incidentally, this can be made safe, but only on a platform with a known
architecture where:

1. There is a strict memory order observed by the hardware platform.

OR

2. You can insert memory barriers at appropriate places to prevent
reordering of memory accesses.

Since Java neither guarantees such hardware nor provides any way of
inserting memory barriers (except from entering or leaving a
synchronized block or method, which will generate memory barriers as
needed for the target hardware), you can't do this in Java. You can't
do it in any portable high-level language, though it's possible in a mix
of some non-Java languages with assembly if you assume a target
hardware.

--
www.designacourse.com
The Easiest Way to Train Anyone... Anywhere.

Chris Smith - Lead Software Developer/Technical Trainer
MindIQ Corporation
 
R

Roedy Green

I'm working with an application that has a couple of singletons and
obviously the member variables are kept separate in the threads that
use the singleton, but I can't find any documentation that explains
the rules.

Design Patterns are not like code or collections. The rules are fuzzy,
and more rules of thumb.

A singleton is by definition unique. It can't have separate variables
for separate threads. So any use of its variables must be shared by
the threads that use it. That means synchronisation to make the
singleton thread safe.

This is more a thread issue than a singleton issue.

see http://mindprod.com/jgloss/thread.html
http://mindprod.com/jgloss/threadsafe.html
 
R

Roedy Green

So the class loader already provides you with lazy instantiation, and
more over provides you with synchronisation. There is just no point to
what you are doing.

Why might you want to postpone creating the singleton past class load
time?

You might have such a case for example if you had a JCE or JDBC-like
scheme for every driver to load sufficiently to register itself. You
just want the stub there, not the works. You could do that of course
by spitting off the registering stuff into its own class and not
touching the singleton class.
 
R

Roedy Green

2. You can insert memory barriers at appropriate places to prevent
reordering of memory accesses.

Is not declaring instance volatile sufficient to make the JVM do
whatever is necessary to avoid such out of order accesses?

The big problem with threads is that any idea you come up with will
work MOST of the time.
 
D

Dave Monroe

Chris Smith said:
Singleton is a pattern, not a specification. There is a description of
the general pattern on page 127 of GoF. In general, Java

What's GoF?
implementations use the static initialization time feature to avoid
overhead when retrieving an object, as such:

public class MySingletonClass
{
private static MySingletonClass instance = new MySingletonClass();

public static MySingletonClass getInstance()
{
return instance;
}

private MySingletonClass() { }

...
}

Unlike similar-looking code in other languages, this will *not* create
an instance of MySingletonClass until the first time getInstance is
called (or the first time MySingletonClass is loaded directly from a
classloader with an explicit request to initialize it). Essentially,
lazy initialization is provided for you as a feature.


What you're describing doesn't really sound like a Singleton at all.
Singletons are shared objects, and are intended that way. They
generally have little or no state at all, and thread-local state is
certainly not a part of the pattern.

They're singletons - trust me.
 

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

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top