It's not a secret anymore!
The moose likes Beginning Java and the fly likes Singleton implementation Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Singleton implementation" Watch "Singleton implementation" New topic

Singleton implementation

vicky malhotra

Joined: Feb 05, 2005
Posts: 16
What is the benefit of using the singleton implementation?
Ilja Preuss

Joined: Jul 11, 2001
Posts: 14112
It's the same as that of a global variable in languages that allow it. It also comes with the same problems, and therefore should be used very carefully.

The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
Jeroen Wenting
Ranch Hand

Joined: Oct 12, 2000
Posts: 5093
The main reason for Singletons is to prevent multiple objects from attempting to access a resource of which there can be only one.
Think of a piece of hardware, a logfile, or a network pipe that needs access control to prevent data corruption.

Robert Hayes
Ranch Hand

Joined: Oct 24, 2004
Posts: 116
I recently read something interesting in Effective Enterprise Java. After talking about ClassLoader isolation issues, Ted says:

Moral: Singletons don't work unless you know where you are in the ClassLoader hierarchy

I thought it was an interesting point...
Jeroen Wenting
Ranch Hand

Joined: Oct 12, 2000
Posts: 5093
Of course. Singletons exist only in the context of a single classloader.
Because each classloader is fully independent (even multiple classloaders inside the same JVM) and a class loaded by one classloader will even have another name as a class loaded by another (even if they're the same compilation unit!) you cannot guarantee that you're truly dealing with a single instance of a class (meaning a single instance created from a single classfile on disk across the entire application) unless you're certain that there's only a single classloader in operation that's loading your classes (there's always one or two more that you have nothing to do with, for example the classloader which loads the JVM itself from the native stub).

But for most programs you can assume that a singleton implementation will be unique at least within the JVM it's running in.
I agree. Here's the link:
subject: Singleton implementation
It's not a secret anymore!