This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
The moose likes Java in General and the fly likes What is singleton class? 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
Bookmark "What is singleton class?" Watch "What is singleton class?" New topic
Author

What is singleton class?

Subrata Pradhan
Greenhorn

Joined: May 05, 2012
Posts: 8
Can anyone please give me detail explanation what is Singletone class or design pattern?? when we are going to use it with example???
Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 60810
    
  65

What is "xyz" questions should always be researched on the web first. Then you can ask specific questions on parts you have trouble understanding.

Singleton pattern


[Asking smart questions] [Bear's FrontMan] [About Bear] [Books by Bear]
Randall Twede
Ranch Hand

Joined: Oct 21, 2000
Posts: 4340
    
    2

true enough Bear. i will just say this. it is a simple version of the answer. when you use singleton pattern you don't have to synchronize any code. i didn't research it beyond that. when you have many clients wanting to access your servlet site you can use singleton pattern to provide each one with their own version of the servlet. that way you don't have to synchronize any of your code. i am sure there is more to it than that.


SCJP
Visit my download page
Anayonkar Shivalkar
Bartender

Joined: Dec 08, 2010
Posts: 1502
    
    5

Randall Twede wrote:when you use singleton pattern you don't have to synchronize any code

I didn't get this. Of course, there will be only one object of that (singleton) class, but what if that same object is shared among threads, and those threads calling methods over that object? I guess it is a typical scenario, and that object is just like any other object.

Or am I missing anything?


Regards,
Anayonkar Shivalkar (SCJP, SCWCD, OCMJD, OCEEJBD)
Junilu Lacar
Bartender

Joined: Feb 26, 2001
Posts: 4447
    
    5

I have doubts about not needing to synchronize when using a singleton, too. In fact, since a singleton introduces what amounts to a global state, one would think that extra care must be taken in accessing any fields in the singleton so that you don't run into any concurrency problem. ThreadLocal objects come to mind to address this. Even early implementations of lazy instantiation of a singleton suffered from synchronization problems. The Wikipedia entry for singleton is pretty complete. In fact, with JEE 6, there are annotations that deal specifically with concurrency concerns: see http://docs.oracle.com/javaee/6/tutorial/doc/gipvi.html. Aside from the instantiation problem though, if the singleton does not have any member fields (that is, it is a stateless singleton) and consists only of methods, then it is going to be inherently thread-safe.

In the strictest sense, a singleton is any class whereby there can exist one and only one instance, universally. A less strict definition would be one and only one instance in a JVM but you need to make sure the class does not make any assumptions that it is universally unique. The typical example I've seen to show the problems that can occur with a (non-strict) singleton that incorrectly assumes it is universally unique is one that implements a counter, without the JEE 6 annotations cited previously. When a singleton like this is deployed to multiple JVMs, then you can start seeing problems.


Junilu - [How to Ask Questions] [How to Answer Questions]
Anayonkar Shivalkar
Bartender

Joined: Dec 08, 2010
Posts: 1502
    
    5

Junilu Lacar wrote:if the singleton does not have any member fields (that is, it is a stateless singleton) and consists only of methods, then it is going to be inherently thread-safe.

How? Again, I'm giving the same scenario I mentioned in previous post. Yes, the class is singleton, and yes, there will be only one object of it throughout the JVM. But what if that same object is shared by many threads, and what if one or more methods of that class is/are dealing with non-threadsafe data structures (like dealing with ArrayList, or developer's own non-threadsafe implementation of queue)?
And again, how this object is different from any other object?
I'm still not getting how thread safety is related to a class being normal one or singleton one.

Apart from that, if a class consists only methods, then I won't even make a single object of it. I would make all those methods as static, and start invoking them

Junilu Lacar wrote:one would think that extra care must be taken in accessing any fields in the singleton so that you don't run into any concurrency problem

Yes. I'm the one (who thinks like that)
Winston Gutkowski
Bartender

Joined: Mar 17, 2011
Posts: 7552
    
  18

Subrata Pradhan wrote:when we are going to use it with example???

Not as often as you'd think.

I believe it was Erich Gamma who said that it was the one design pattern that, with hindsight, he would have left out of "the book".

Winston


Isn't it funny how there's always time and money enough to do it WRONG?
Articles by Winston can be found here
Junilu Lacar
Bartender

Joined: Feb 26, 2001
Posts: 4447
    
    5

Anayonkar Shivalkar wrote:
How? ... how this object is different from any other object?
I'm still not getting how thread safety is related to a class being normal one or singleton one.


Concurrency issues need to be considered when there is a possibility of multiple threads accessing information held by an object at the same time. To defend against problems, you serialize, i.e. synchronize, access to the shared information. If there is no shared information to be accessed, then there is no concurrency issue. Remember, method parameters are thread-safe and so are objects/variables local to the method. If you make calls to other methods, even methods of other objects, any parameters or local values you pass to those methods remain thread-safe.

How is it related to a class being normal and multi-instanced vs being a singleton, albeit perhaps a loosely-defined singleton? No relationship really, except for the fact that in both cases you need to be mindful of concurrency issues. I was actually trying to qualify Randall's statement about concurrency being a non-issue with a singleton class: it's true only if it's stateless. Otherwise, a stateful singleton has the same concurrency issues as any other "regular" class.

Apart from that, if a class consists only methods, then I won't even make a single object of it. I would make all those methods as static, and start invoking them


You could do that but you would be ruining a perfectly pure and safe stateless object. Why do you think having no state warrants stripping away the need to instantiate a class? Note that servlets are supposed to be like this (the pure, stateless kind of object, that is). Have you ever read the advice to NOT have any member fields in a servlet? If you don't follow that advice, then you can run into concurrency problems. Same deal. And servlets are often (but as others have pointed out, not always) the kind of singleton you speak of: one per JVM.

Also note that in frameworks like Spring, beans that the framework manages are, by default, the loosely-defined singletons we've been talking about. And the same things above apply. Why/how a lot of people use Spring and singletons safely is a whole nother topic though
Anayonkar Shivalkar
Bartender

Joined: Dec 08, 2010
Posts: 1502
    
    5

Thanks for the answer Junilu Lacar.

Its pretty clear now
Junilu Lacar
Bartender

Joined: Feb 26, 2001
Posts: 4447
    
    5

Glad to be of help.

One more note, regarding method parameters being thread-safe. This is assuming that the value was passed in a thread-safe manner. Otherwise, all bets are off. A good example of this is when you pass an object as a parameter to a method. While parameters are always passed by value in Java, passing an object passes a copy of the reference to that object. (I'm sure you can find other threads that go into detail about this). If the object that the parameter references happens to be one that can be accessed by multiple threads in an unsafe manner in the caller, e.g. it is an instance member in the calling class, then your parameter also becomes iffy with respect to thread safety.

Example:



Exercise: make changes so all code is thread-safe.
Adam Zehavi
Greenhorn

Joined: Jun 03, 2012
Posts: 11
WOW guys... such a mess over a Singleton...

I wrote this post about Singletons and Android, a while back, as I was frustrated with Android developer over abusing the Singleton pattern in an app.
It also discusses some of the facts about the Singleton, and I think it speaks for this thread.

In any case, a singleton MAY be synchronized as necessary, and in some cases it does, and it depends on the implementation of it!
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: What is singleton class?
 
Similar Threads
wat is singletone
Singletone Pattern
singletone pattern
Data: Mutition/Singletone
Difference between in making a class as singletone and