wood burning stoves 2.0*
The moose likes Java in General and the fly likes 2 different types of singleton Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Java in General
Reply locked New topic
Author

2 different types of singleton

saikrishna cinux
Ranch Hand

Joined: Apr 16, 2005
Posts: 689
hi can any one tell me what is the difference in these 2 classes i cam create only one instance with bothe singleton classes



A = HARDWORK B = LUCK/FATE If C=(A+B) then C=SUCCESSFUL IN LIFE else C=FAILURE IN LIFE
SCJP 1.4
Aditya Jha
Ranch Hand

Joined: Aug 25, 2003
Posts: 227

Hi Sai,

Both classes are fine as long as you are in a single-threaded mode. However, when you need your singleton class to be thread-safe (to be able to guarantee at most one instance even if multiple threads work on it), there is a little difference.

In the first class, instantiation of the singleton instance is done inside the getInstance() method. This method is not synchronized. Hence, two different threads may access it simultaneously. In such a scenario, it is possible that the null-check and instantiation are done by both the threads. This will result in two instances of the class (or for that matter, theoritically, n instances for n number of threads).

One way to ensure thread-safety is to make method getInstance() synchonized.

Another way to make the class thread-safe is shown in the second class, where the private static reference to the singleton object is initialized at the time of declaration only. This initialization will obviously be done at the time of class-loading (as the property is static). Hence, an instance will be created before making the method accessible to any thread. After this, no matter how many threads access the method getInstance() they will recieve references of a single object. In such a scenario, it is obviously unnecessary to make the method getInstance() synchronized (and is recommended to not to make it synchronized as a call to a synchronized method can be many times slower that that to a un-synchronized method).

Hope this helps.

Cheers!
- Aditya
saikrishna cinux
Ranch Hand

Joined: Apr 16, 2005
Posts: 689
so , which code is better to use.
can i use the second code?i think it will be little bit faster
Tad Dicks
Ranch Hand

Joined: Nov 16, 2004
Posts: 264
You could also look at the double checked singleton:



This keeps down the overhead of instantiating an object that might never be used/needed and only performs the relatively more resource expensive synchronized method a single time.
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24183
    
  34

Originally posted by Tad Dicks:
You could also look at the double checked singleton:


No, no, no, no, NO, NO, NO!

As has been documented countless times, and discussed countless more times on this very site, this does not work and is not thread safe!

There are three choices that work. The simplest is the initialized static member version. The second is the synchronized getInstance() method. The third one is to use an extra class, a static member class, which hold nothing but the initialized static member; the getInstance() method can then reference it. The static member class will only be loaded, and the singleton instantiated, when getInstance() is called.

But in any case, synchronization is very cheap. Attempts to avoid it on performance grounds are ill-advised, especially when, as in the double-checked locking example, they lead to broken code.


[Jess in Action][AskingGoodQuestions]
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
Originally posted by Tad Dicks:
You could also look at the double checked singleton:


Beware though - before Java 5, double checked locking didn't work reliably.


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
Ken Blair
Ranch Hand

Joined: Jul 15, 2003
Posts: 1078
Originally posted by Ilja Preuss:


Beware though - before Java 5, double checked locking didn't work reliably.


It still doesn't if the variable isn't volatile. The costs associated with volatile variables in the new memory model means you still don't get a performance gain out of it either.
Ken Blair
Ranch Hand

Joined: Jul 15, 2003
Posts: 1078
Originally posted by Ernest Friedman-Hill:
There are three choices that work. The simplest is the initialized static member version. The second is the synchronized getInstance() method. The third one is to use an extra class, a static member class, which hold nothing but the initialized static member; the getInstance() method can then reference it. The static member class will only be loaded, and the singleton instantiated, when getInstance() is called.


Which is typically called the Initialization on Demand Holder idiom. I bring it up only to make finding more information easier. Here's an example of what Ernest is talking about:



The only reason to use this is if the Singleton class will be initialized before you wish the actual instance to be created. In this case the Singleton will be initialized but not the SingletonHolder so the actual instance will not be created until getInstance() itself is called. Note that class loading and initialization are not the same thing, there's a very common misconception that class variable initializers and static initialization blocks are executed when the class is loaded. That's simply not accurate, however in most cases initialization does happen immediately because the class was used for the first time in a way that requires both.
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18542
    
  40

Originally posted by Ken Blair:

It still doesn't if the variable isn't volatile. The costs associated with volatile variables in the new memory model means you still don't get a performance gain out of it either.


Another issue is that with Java 5, synchronization is so much faster, that bar to beat has also been significantly raised.

To repeat EFH... No, no, no, no, NO, NO, NO!

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Tad Dicks
Ranch Hand

Joined: Nov 16, 2004
Posts: 264
Hrm... I haven't seen it mentioned here, but I did read that pattern in the Head First object patterns book and a quick search brought up the pattern on an IBM site.

Well I'm glad I posted erroneously, otherwise I would have never known. I guess I will go look for the thread that explains why this doesn't work.
Ken Blair
Ranch Hand

Joined: Jul 15, 2003
Posts: 1078
http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html
Tad Dicks
Ranch Hand

Joined: Nov 16, 2004
Posts: 264
Thank you for the link.
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
[Tad]: Hrm... I haven't seen it mentioned here, but I did read that pattern in the Head First object patterns book and a quick search brought up the pattern on an IBM site.

Note that Head First Design Patterns does specifically say that the pattern only works if the variable is volatile, and only in JDK 5 or later. Which is quite true. The book does fail to account for the various other points raised by EFH, Henry, and Ken, which I agree with: even if it works in JDK 5, it's generally not worth the trouble. Straight synchronization is at least as fast and less error-prone, and the initialization-on-demand holder is even better (if less well-known).

As for the article on the IBM site - yo9u mean this one? Note the subtitle: "A comprehensive look at this broken programming idiom". Or if you found a different article, please look again: most articles available today take pains to point out the problems with double-checked locking.


"I'm not back." - Bill Harding, Twister
Tad Dicks
Ranch Hand

Joined: Nov 16, 2004
Posts: 264
Note that Head First Design Patterns does specifically say that the pattern only works if the variable is volatile, and only in JDK 5 or later.


I read through most of the book several months ago and was going from memory... I did a quick search and found a link to the code. I will admit I was just looking for a code snippet that matched what I remember reading in the book. My bad.

I'm going to blame it all on the .NET programming I've been forced to do for the last 6 months.
Tony Morris
Ranch Hand

Joined: Sep 24, 2003
Posts: 1608
...and after all that, it's not a singleton at all, since no such thing exists. It is merely class loader scoped data.


Tony Morris
Java Q&A (FAQ, Trivia)
saikrishna cinux
Ranch Hand

Joined: Apr 16, 2005
Posts: 689
Hi, to all

my dear rancher's just see my very first thread :roll: ...
what i've asked and what you are explaining me???
i'm not getting anything
please tell me the actual singleton class from those 2 programs....

which is the better singleton design patter program

any way thank's to all
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
See the very first response. Either style is fine. There is some difference in when the single instance is created which may or may not matter in your programs.

It would be wise to synchronize the first one just in case it is used in a multi-threaded program one day. The overhead of a synchronized method is not a big problem here. The method will take long enough to create an instance the first time it is called, otherwise it will be too fast to measure. The overhead of the "if null" test is nothing to worry about.

I use the second style most of the time just because it feels cleaner. There are other ways to create singletons, but they rapidly get too advanced for this forum.

And keep Tony's note in mind even if it doesn't make a lot of sense yet. These techniques give us one instance per class loader. It's easy to accidentally make more instances with other class loaders. It's very hard to ensure there is exactly one instance in a JVM. If you write the kind of systems where somebody could die if there are two instances, get expert help.


A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
saikrishna cinux
Ranch Hand

Joined: Apr 16, 2005
Posts: 689
Thanks stan, but can u provide me an advanced version of singleton design patter program so that it must be compatible to all the classloaders available in the market

thanks
ak pillai
author
Ranch Hand

Joined: Feb 11, 2006
Posts: 288
For a global singleton, you need to use an independent service like a RMI service, which can be shared between applications.


java j2ee job interview questions with answers | Learn the core concepts and the key areas
Tony Morris
Ranch Hand

Joined: Sep 24, 2003
Posts: 1608
Originally posted by ak pillai:
For a global singleton, you need to use an independent service like a RMI service, which can be shared between applications.


For a global singleton, you need to prove that the universe is finite and then assert that there exists only "one" in (finite) spacetime. What you have described is not a singleton, but merely "application scoped data". All data is scoped within some finite boundary (be it a local declaration or higher), therefore, either all data is a singleton or no data is a singleton. I am opting for the latter definition.
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
Originally posted by Tony Morris:

For a global singleton, you need to prove that the universe is finite and then assert that there exists only "one" in (finite) spacetime.


Actually not, no. "Global" comes from "globe", which refers only to our earth, not to the whole universe, let alone multiverse.
saikrishna cinux
Ranch Hand

Joined: Apr 16, 2005
Posts: 689
Originally posted by Tony Morris:


For a global singleton, you need to prove that the universe is finite and then assert that there exists only "one" in (finite) spacetime. What you have described is not a singleton, but merely "application scoped data". All data is scoped within some finite boundary (be it a local declaration or higher), therefore, either all data is a singleton or no data is a singleton. I am opting for the latter definition.


so, u mean there is no perfect design pattern for making a single instance(Singleton ) globally

if i use this singleton in webapplication it wont work.(coz tomcat and weblogic servers uses their own classloaders )

hence i can prove that singleton is an anti patter it's not a design pattern
Pradeep bhatt
Ranch Hand

Joined: Feb 27, 2002
Posts: 8904

You can bind your singelton instance to the JNDI tree,


Groovy
Ken Blair
Ranch Hand

Joined: Jul 15, 2003
Posts: 1078
Originally posted by Tony Morris:


For a global singleton, you need to prove that the universe is finite and then assert that there exists only "one" in (finite) spacetime. What you have described is not a singleton, but merely "application scoped data". All data is scoped within some finite boundary (be it a local declaration or higher), therefore, either all data is a singleton or no data is a singleton. I am opting for the latter definition.


Or your definition of Singleton differs from other posters. Isn't it possible the rest of us consider a class for which there can only exist a single instance per class loader a "Singleton"?
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
if i use this singleton in webapplication it wont work.(coz tomcat and weblogic servers uses their own classloaders )

hence i can prove that singleton is an anti pattern it's not a design pattern

You just need to work harder to make sure you are using the same class loader every time you reference the singleton's getInstance method. It's possible but not fun.

You can temporarily define terms to whatever they means to you, but make sure everyone in the conversation knows and agrees. "Singleton" commonly means "one instance per JVM" and "global" is probably "accessible by any object in the JVM" or maybe in the scope of the class loader that loaded the application code (opposed to the container code.) If we agree to some definition for a few moments, we can ignore rest of the cosmos.
Tony Morris
Ranch Hand

Joined: Sep 24, 2003
Posts: 1608
Originally posted by Ken Blair:


Or your definition of Singleton differs from other posters. Isn't it possible the rest of us consider a class for which there can only exist a single instance per class loader a "Singleton"?


Sure it's possible.

I have a few questions then:
1) Under this definition, every static member is a "singleton" - you must agree or shift the definition
2) Every "class" is a singleton - again, agree or shift
3) Aren't "design patterns" supposedly "language agnostic"? Isn't it then a contradiction within its very own definition? Shift the definition of design pattern or singleton - as it stands, they are orthogonal. Simply, a "singleton" is not a design pattern, and every static member is a singleton - why not just call it a static member?
4) Why "class loader"? Why some arbitrary scope? "Because the book said so" is my best explanation so far - which I simply don't buy. How about "because the establishment said so"? Again, history shows that established beliefs are - if anything - generally false. Therefore, it is not sound evidence. Or simply, "because everyone else said so" is void. Any other explanations are welcome.

I blame the illegitimate authoritarian texts that claim to purport truth and naive subscribers willingly bow down - this side issue has resulted in my declaration of being a sworn enemy to what I perceive as nonsense and exploitation of those who have no choice but to trust the word of others. The exploitation may be intentional or not, but is irrelevant to the issue at hand.

Unfortunately (for myself more often than not), I am an optimist, hence my continual rant.
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
Most of us are pretty willing to take the folding and spindling and other mutiulation Java applies to object oriented stuff and just do our best. Tony has the curse of caring more about the details than, say, me. I have pretty high hopes that his point of view will eventually improve the world while I'm happy to eak out a living. I await the next, more perfect language.

The one-line description of Singleton in GoF is "Ensure a class has only one instance, and provide a global point of access to it." In the following discussion "well-known" sometimes replaces "global".

They didn't define the scope for the one instance. It's probably not "in the cosmos from the beginning of time until the end of time". If it's something less than that we can make it whatever fits the language and the job. If the language doesn't quite measure up to the book, should we forbid the word "Singleton" in Java? Nah. Just know what it means in Java, know whether it solves the problem at hand, and get on with it.

I use Singleton for caches now & then. I know that one instance of some object per user or per request would be "too many" and I'd be happy to approach one per JVM. If I get confused about class loaders and have two per JVM nobody dies. If I get really confused and wind up with thousands again, that's a bug on my part, I have to work harder at it.

For your questions ...

1) Every static member is a Singleton? Doesn't quite match GoF, does it? If the member is an Object there is a single object reference per class per loader. Unless each object reference is an instance of a unique class then I don't think we have a single instance of any class.

2) Every class is a singleton? There is a single something (per loader) in memory for each class. But I think it's an instance of Class, so there are many instances of Class ... not singleton.

3) Patterns language agnostic? Yup, until you have to implement them. If we want to say Java is so damaged that you cannot do Singleton, do we need to make up a new name for "single instance per class loader"? Mingleton? Schmingleton?

4) Why class loader scope? A side effect of the language design. Not because "a book said so" but because the JVM works that way for the simple (and usually sufficient) implementation.

BTW: I'm perfectly willing to be shown wrong on any of those. Tony, your posts are most always educational if a bit vexing.

Some questions of my own ... Should we develop something that assures one instance per JVM with tricky class loader manipulation? Should we press Sun to give us new syntax to guarantee one instance per JVM?
Ken Blair
Ranch Hand

Joined: Jul 15, 2003
Posts: 1078
Originally posted by Tony Morris:


Sure it's possible.

I have a few questions then:
1) Under this definition, every static member is a "singleton" - you must agree or shift the definition
2) Every "class" is a singleton - again, agree or shift
3) Aren't "design patterns" supposedly "language agnostic"? Isn't it then a contradiction within its very own definition? Shift the definition of design pattern or singleton - as it stands, they are orthogonal. Simply, a "singleton" is not a design pattern, and every static member is a singleton - why not just call it a static member?
4) Why "class loader"? Why some arbitrary scope? "Because the book said so" is my best explanation so far - which I simply don't buy. How about "because the establishment said so"? Again, history shows that established beliefs are - if anything - generally false. Therefore, it is not sound evidence. Or simply, "because everyone else said so" is void. Any other explanations are welcome.

I blame the illegitimate authoritarian texts that claim to purport truth and naive subscribers willingly bow down - this side issue has resulted in my declaration of being a sworn enemy to what I perceive as nonsense and exploitation of those who have no choice but to trust the word of others. The exploitation may be intentional or not, but is irrelevant to the issue at hand.

Unfortunately (for myself more often than not), I am an optimist, hence my continual rant.


1. A static member is not a class.
2. There exist many instances of Class.
3. I'm not experienced or knowledgeable enough to dare make sweeping statements about "design patterns" or OOP, so whether or not a design pattern is by definition "language agnostic" I'll have to defer on. That being said it is my impression that when referring to design patterns we're talking about solutions to common problems in object oriented software design. As far as I'm aware there is no accepted formal definition for Singleton that implies it must be one instance per universe, solar system, planet, continent, application, era, year, machine, language, etc. In other words, when talking about a Singleton we're talking about a class that is designed such that there can only be one instance. In what context this is depends on the discussion.
4. I would think it's because a Singleton in the context of "per ClassLoader" is the most commonly used and has the behavior most commonly expected. Admittedly, I can't back this up, it's just an opinion based entirely on experience which is limited. If I break out my GoF book (which you may not consider an authorative source) and I take a look at the intent, motivation, applicability, structure, participants, collaboration and consequences I think the "per ClassLoader" definition and solutions most closely resemble the pattern and the most common uses in Java applications.
Ken Blair
Ranch Hand

Joined: Jul 15, 2003
Posts: 1078
Stan's post more or less communicates what I wanted to better than I did. I started writing mine and was pulled away from it for almost an hour so I missed it.
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
I mostly agree with what Stan and others have said, I just want to add the following:

I think the basic ideas of the patterns are more or less language agnostic, although some of them don't make much sense in some languages. (For example, Visitor is rather useless in a language that supports multi methods, as far as I can tell.)

But at the low level, design itself is not at all language agnostic - because different languages give us different tools and constraints, design details are language sensitive. So the implementation details of design patterns certainly are, too.

I don't see that as a problem, though. Design patterns aren't meant to be implemented as-is, anyway - they are templates that are to be adapted to specific situations. If that context includes the implementation language, I don't see any problem with it.

It's true, to come back to the example, that there are some things about the Singleton pattern that are special in Java. That needs to be said, but once it is, the pattern can still help you get what it is intended to give you by the original authors.
Tony Morris
Ranch Hand

Joined: Sep 24, 2003
Posts: 1608
Originally posted by Ken Blair:


1. A static member is not a class.
2. There exist many instances of Class.
3. I'm not experienced or knowledgeable enough to dare make sweeping statements about "design patterns" or OOP, so whether or not a design pattern is by definition "language agnostic" I'll have to defer on. That being said it is my impression that when referring to design patterns we're talking about solutions to common problems in object oriented software design. As far as I'm aware there is no accepted formal definition for Singleton that implies it must be one instance per universe, solar system, planet, continent, application, era, year, machine, language, etc. In other words, when talking about a Singleton we're talking about a class that is designed such that there can only be one instance. In what context this is depends on the discussion.
4. I would think it's because a Singleton in the context of "per ClassLoader" is the most commonly used and has the behavior most commonly expected. Admittedly, I can't back this up, it's just an opinion based entirely on experience which is limited. If I break out my GoF book (which you may not consider an authorative source) and I take a look at the intent, motivation, applicability, structure, participants, collaboration and consequences I think the "per ClassLoader" definition and solutions most closely resemble the pattern and the most common uses in Java applications.


1. A static member is class-loader scoped data, therefore, it fits your definition of "singleton" and so is a singleton.
2. A Class is class-loader scoped data, therefore, it is a "singleton".
3. I'll shorten the research for you, singleton is not a "design pattern" - in fact, no such thing (design pattern) really exists - one need only start looking at the mathematical foundations of requirements analysis to deduce this somewhat simple and obvious conclusion. Like a singleton, one can continually shift definitions recursively (it is recursive - just watch someone try to say that points 1 and 2 are wrong by shifting definition) in an attempt to save some notion that one may (unfortunately) be attached to in some way - even if some party were to hold conclusive proof before the subject.
4. Fine, I now call all class-loader scoped data "singleton". This will be fun By the way, what happens when there are 2 class loaders? Oh wait, the books don't ever do that. Here is what I once thought (until now in order to be socially compliant) was a singleton:

The local declaration 'singleton' is a singleton - only one exists in the scope given by a pair of braces. One may define a new pair of braces with a different "singleton", but they are still both a singleton.

Here is another singleton:

The field declaration singleton is a singleton - only one exists in the scope of an instance of Y. One may define a new instance of Y, but they are still both singletons.

Here is another one:

The static field declaration singleton is a singleton - only one exists in the scope of Z.class and only one Z.class exists within the scope of a class loader. This singleton also fits my new (ok, I am being facetious) definition of singleton, since the books (or is it "everyone else"?) said so.

I offer you an experiment - a thought experiment. Put yourself in a cage for 50 years. In those 50 years, you are placed under duress and forced to write software - call it say, WebSphere. In that software, you are responsible for one specific part of it - one that involves using different class loaders several times a day. You quickly learn that something that exists in one class loader may also exist in another class loader (but in a different point in spacetime). After 50 years you exit the cage, and you denounce any notion of a "singleton being class loader scoped" data, however, you find that "everyone else" - who rarely does what you do - believes otherwise.

The question now is, is it simply the "community standard" that defines a singleton (pulled from books, etc.)? If not, then is the definition of the aforementioned caged subject illegitimate? Or can both definitions exist independently? For example, I might have a notion of a singleton, today, and I might have a different definition tomorrow as might you (anyone). All definitions are legitimate and a "singleton" therefore exists "in one's head".

Just which is it?
Ken Blair
Ranch Hand

Joined: Jul 15, 2003
Posts: 1078
Originally posted by Tony Morris:

1. A static member is class-loader scoped data, therefore, it fits your definition of "singleton" and so is a singleton.



The definition I offered was not "class-loader scoped data", it explicitly required it to be a class and that only one instance could exist in a given class loader.

Originally posted by Tony Morris:

2. A Class is class-loader scoped data, therefore, it is a "singleton".



Not by the definition I offered, it certainly isn't. There's more than one instance of Class and therefore by the definition I offered it would not be a Singleton.

Originally posted by Tony Morris:

3. I'll shorten the research for you, singleton is not a "design pattern" - in fact, no such thing (design pattern) really exists - one need only start looking at the mathematical foundations of requirements analysis to deduce this somewhat simple and obvious conclusion. Like a singleton, one can continually shift definitions recursively (it is recursive - just watch someone try to say that points 1 and 2 are wrong by shifting definition) in an attempt to save some notion that one may (unfortunately) be attached to in some way - even if some party were to hold conclusive proof before the subject.



I don't understand most of that paragraph, however I take from it one point you're trying to make is that we can continually change definitions and redefine terms to hold on to a belief even when there's proof to the contrary.

Originally posted by Tony Morris:

4. Fine, I now call all class-loader scoped data "singleton". This will be fun By the way, what happens when there are 2 class loaders? Oh wait, the books don't ever do that. Here is what I once thought (until now in order to be socially compliant) was a singleton:



But that still doesn't fit the definition I mentioned. If it's not a class or if there can be more than one instance of that class per class loader then it doesn't hold. No shifting of definitions is necessary, it doesn't meet the definition to begin with.

Originally posted by Tony Morris:

The local declaration 'singleton' is a singleton - only one exists in the scope given by a pair of braces. One may define a new pair of braces with a different "singleton", but they are still both a singleton.

Here is another singleton:

The field declaration singleton is a singleton - only one exists in the scope of an instance of Y. One may define a new instance of Y, but they are still both singletons.

Here is another one:

The static field declaration singleton is a singleton - only one exists in the scope of Z.class and only one Z.class exists within the scope of a class loader. This singleton also fits my new (ok, I am being facetious) definition of singleton, since the books (or is it "everyone else"?) said so.



None of those meet the definition I gave.

Originally posted by Tony Morris:

I offer you an experiment - a thought experiment. Put yourself in a cage for 50 years. In those 50 years, you are placed under duress and forced to write software - call it say, WebSphere. In that software, you are responsible for one specific part of it - one that involves using different class loaders several times a day. You quickly learn that something that exists in one class loader may also exist in another class loader (but in a different point in spacetime). After 50 years you exit the cage, and you denounce any notion of a "singleton being class loader scoped" data, however, you find that "everyone else" - who rarely does what you do - believes otherwise.

The question now is, is it simply the "community standard" that defines a singleton (pulled from books, etc.)? If not, then is the definition of the aforementioned caged subject illegitimate? Or can both definitions exist independently? For example, I might have a notion of a singleton, today, and I might have a different definition tomorrow as might you (anyone). All definitions are legitimate and a "singleton" therefore exists "in one's head".

Just which is it?


I don't think your definition is illegitimate. An infinite number of definitions could exist independently. However, if the "community" uses one definition and you use another then you can't expect the "community" to know you're not using the same definition when you say that a Singleton doesn't exist. I realize the "community" can't agree on much of anything but it seems to me what most people mean by "Singleton" in this context is pretty close, if not exactly the same, to what I said.

That was, more or less, my point. You consistently say that there is no such thing as a Singleton, however the examples you give and the arguments you make seem to indicate to me that you simply aren't working off of the same definition.
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
Originally posted by Tony Morris:
The question now is, is it simply the "community standard" that defines a singleton (pulled from books, etc.)?


I'm not sure about the term singleton.

I'm sure about the design pattern Singleton, though, and yes - it means exactly what the design pattern community wants it to mean. That's exactly how design patterns come into being - by being observed and given a name by the community.
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
The shared understanding of meaning is about the only value of any word. Most of the folks here can use "Singleton" in a conversation together with a sufficiently similar understanding of what is meant, with its limitations, warts and all. Tony uses "singleton" with small "s" in a very precise way that I'll trust is meaningful in language theory and beautifully self consistent with the rest of his thinking, but nearly useless in conversation with the bulk of the intermediate forum.
Tony Morris
Ranch Hand

Joined: Sep 24, 2003
Posts: 1608

You consistently say that there is no such thing as a Singleton, however the examples you give and the arguments you make seem to indicate to me that you simply aren't working off of the same definition.

It seems we have consensus then - a singleton is merely a community standard - transgressing the original definition proposed by GoF.

I'll clear up the above point. When I have said "a singleton does not exist", I was inaccurate and instead should have said, "one of the following is true: everything is a singleton, nothing is a singleton or the definition of a singleton is relative to the observer (i.e. exists in one's head only)". We have agreed that it is the latter that is true. Taking it to an extreme we could say that the latter point is definitely true if what we know of the nature of the speed of light is definitely true, but we all know that the laws of the universe and software are orthogonal and appear unrelated to a casual observer
saikrishna cinux
Ranch Hand

Joined: Apr 16, 2005
Posts: 689
oh,man you are now making a relationship with physical sciences
PLEASE ,dont compare java, and computer fundamentals with physics,maths or any other scrap
Tony Morris
Ranch Hand

Joined: Sep 24, 2003
Posts: 1608
Originally posted by saikrishna cinux:
oh,man you are now making a relationship with physical sciences
PLEASE ,dont compare java, and computer fundamentals with physics,maths or any other scrap


Computational progression requires time (and therefore space) in order to exist. The laws of the physics are what makes Java possible even if indirectly or not immediately obvious. I had already put the disclaimer in place anyway; the casual observer will not see the correlation. It simply isn't taught at school despite being of utmost importance (market pressures aside).
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
Originally posted by saikrishna cinux:
or any other scrap


Watch your language, please. We should be able to disagree with each other without becoming abusive. Keep in mind that misunderstandings are prevalent in written communication, and that we therefore have to be more careful here than in face to face conversations.
Vj Kamath
Greenhorn

Joined: Nov 19, 2004
Posts: 15
Aditya N Jha wrote:
In the first class, instantiation of the singleton instance is done inside the getInstance() method. This method is not synchronized. Hence, two different threads may access it simultaneously. In such a scenario, it is possible that the null-check and instantiation are done by both the threads. This will result in two instances of the class (or for that matter, theoritically, n instances for n number of threads).


As per my understanding, multiple Instances will NOT be created. There will be a new instance and the old instance will be garbage collected.

Note the code

and the code


The s will get the reference to the new Singleton object. The old object will get Garbage collected. Ofcourse this will defeat the purpose of Singleton as you rightly pointed out. But my point is that we won't have n instances for n number of threads. Please correct me if my understanding is incorrect.
saikrishna cinux
Ranch Hand

Joined: Apr 16, 2005
Posts: 689
Originally posted by Ilja Preuss:


Watch your language, please. We should be able to disagree with each other without becoming abusive. Keep in mind that misunderstandings are prevalent in written communication, and that we therefore have to be more careful here than in face to face conversations.


sorry Mr morris, that was not intentionally done. it's my usaual way of talking,
so misunderstand me Mr Ilja,
thank you for ur valuable suggestion u r right that face to face conversation is different from written communication,I Agree
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: 2 different types of singleton
 
Similar Threads
Combining State and Singleton design patterns
doubt about MasterExam question
Singleton
singleton class
Should the Singleton instance be a final variable?