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