• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Singleton implementation

 
vicky malhotra
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What is the benefit of using the singleton implementation?
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Jeroen Wenting
Ranch Hand
Posts: 5093
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 116
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 5093
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic