aspose file tools*
The moose likes Beginning Java and the fly likes Singleton pattern Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Singleton pattern" Watch "Singleton pattern" New topic
Author

Singleton pattern

abalfazl hossein
Ranch Hand

Joined: Sep 06, 2007
Posts: 635
[/code]

from:THE
DESIGN PATTERNS
JAVA COMPANION

I understand Singleton is used when you want oly have one instance.

May you show me what is the usage of Singleton by a simple example?
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14103
    
  16

That is not a great way to implement a singleton... there are much better ways to implement the singleton pattern in Java. I suggest you forget the code from that book!

Sometimes you need to have exactly one instance of a class. For example for a class that represents a printer, as in your example: there is just one physical printer, so you want exactly one instance of your class that represents the printer in your application.


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
Hunter McMillen
Ranch Hand

Joined: Mar 13, 2009
Posts: 492

The classic way of creating a singleton is to make the constructor of the class private.

ex:



And when you are trying to use the PrintSpooler instance, you would do this



Hope that helps
Hunter


"If the facts don't fit the theory, get new facts" --Albert Einstein
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14103
    
  16

You need to make the getInstance() method synchronized, otherwise two threads calling the method simultaneously might cause two instances to be created.
Hunter McMillen
Ranch Hand

Joined: Mar 13, 2009
Posts: 492

I didn't see any mention of threads above so I posted the simplest example I could think of.


Hunter
James Sabre
Ranch Hand

Joined: Sep 07, 2004
Posts: 781

Jesper de Jong wrote:You need to make the getInstance() method synchronized, otherwise two threads calling the method simultaneously might cause two instances to be created.


Has the memory model changed so that double-checked locking is no longer flawed in the way outlined in http://www.ibm.com/developerworks/java/library/j-dcl/index.html ?


Retired horse trader.
 Note: double-underline links may be advertisements automatically added by this site and are probably not endorsed by me.
Mike Simmons
Ranch Hand

Joined: Mar 05, 2008
Posts: 3007
    
    9
Yes, since JDK 1.5 - it works as long as you declare the variable as volatile. Though 1.5 also introduced enums, which give an even easier way to create a singleton:

So double-checked locking doesn't really have much use, still.
James Sabre
Ranch Hand

Joined: Sep 07, 2004
Posts: 781

Mike Simmons wrote:Yes, since JDK 1.5 - it works as long as you declare the variable as volatile.

Interesting! I shall have to research this.

Though 1.5 also introduced enums, which give an even easier way to create a singleton:

So double-checked locking doesn't really have much use, still.

I converted to this pattern some while ago but since I don't use many singletons it was fairly straightforward.
Mike Simmons
Ranch Hand

Joined: Mar 05, 2008
Posts: 3007
    
    9
A good overview with links to more detailed materials: Java Memory Model.
Abhay Agarwal
Ranch Hand

Joined: Feb 29, 2008
Posts: 1086
    
    1


@abalfazl hossein -- you can follow below mentioned link to know singleton pattern in simple example
http://www.oodesign.com/singleton-pattern.html
abalfazl hossein
Ranch Hand

Joined: Sep 06, 2007
Posts: 635
Is using a private constructor the only way in order to create singleton pattern?
Mike Simmons
Ranch Hand

Joined: Mar 05, 2008
Posts: 3007
    
    9
Considering that I've already shown another way above, the answer would be no.
Pat Farrell
Rancher

Joined: Aug 11, 2007
Posts: 4646
    
    5

Please consider not using a Singleton pattern. They are grossly overused.

All a Singleton is, really, is a global wad of data. It breaks cohesion, increases coupling, and makes unit testing nearly impossible.
Wouter Oet
Saloon Keeper

Joined: Oct 25, 2008
Posts: 2700

Pat Farrell wrote:Please consider not using a Singleton pattern. They are grossly overused.

All a Singleton is, really, is a global wad of data. It breaks cohesion, increases coupling, and makes unit testing nearly impossible.

I don't see how a singleton breaks cohesion.


"Any fool can write code that a computer can understand. Good programmers write code that humans can understand." --- Martin Fowler
Please correct my English.
Pat Farrell
Rancher

Joined: Aug 11, 2007
Posts: 4646
    
    5

Wouter Oet wrote:I don't see how a singleton breaks cohesion.

Using a singleton as a global wad of data enables classes to use the global data. That means code all over the place is accessing code in the wad-o-global data, the very definition of a lack of cohesion.

By definition, when one class deals directly with methods and variables from another, that is the definition of close coupling.
Matthew Brown
Bartender

Joined: Apr 06, 2010
Posts: 4363
    
    8

Oh, I'd agree that it's close coupling. And I'd agree about the unit testing. And those are enough to avoid singletons in most cases. But cohesion? If the singleton has a single, well-defined purpose, then it's cohesive by definition. Not that that changes the general point.
Pat Farrell
Rancher

Joined: Aug 11, 2007
Posts: 4646
    
    5

The singleton is cohesive within itself. Which is generally a good thing. But cohesion between classes can be bad. Cohesion between classes in separate packages is very bad -- it is also called coupling.
Hunter McMillen
Ranch Hand

Joined: Mar 13, 2009
Posts: 492

But from the point of view of the Printer example in the original post, it makes sense to only have one printer regardless of how many other classes exist within your application. The amount of coupling that occurs is bad from a design perspective, but it models the real world in this case.



Hunter
Pat Farrell
Rancher

Joined: Aug 11, 2007
Posts: 4646
    
    5

Hunter McMillen wrote:But from the point of view of the Printer example in the original post, it makes sense to only have one printer regardless of how many other classes exist within your application. The amount of coupling that occurs is bad from a design perspective, but it models the real world in this case.


I am not saying that it is bad to only have one instance of your Printer class.

What I am saying is that the Singleton Pattern (Copyright Gang of Four book) is bad. There are many other ways to have one and only one instance of the Printer object. A PrinterFactory is the obvious one.

While folk in Beginning Java will probably not run into it, there are many serious subtle errors that come up when you are doing serious code with the Singleton Pattern. Since you can achieve the same goal without the baggage and bugs of the Singleton Pattern, I believe that it is never too soon to learn how dangerous it is.

The alternative is easy. But unless folks know to ask, they won't look for one.

Wouter Oet
Saloon Keeper

Joined: Oct 25, 2008
Posts: 2700

Wikipedia about Singleton wrote:In software engineering, the singleton pattern is a design pattern used to implement the mathematical concept of a singleton, by restricting the instantiation of a class to one object.

So if you write a Factory method which only returns a single instance of some type then that is a instance is an singleton. Remember that a pattern is just a description and not an implementation.
Wim Vanni
Ranch Hand

Joined: Apr 06, 2011
Posts: 96

Seems to me like the original poster got more than he bargained for

He must feel like the Karate Kid who learned the special move of the 'crane' and found out that he is nothing with it when his opponent knows the proper move to block it

To remember, in my opinion:

- the original implementation would effectively create a Singleton but is not an elegant way to do it
- Hunter's code, making use of a private constructor and getInstance() is how the GoF (Gang Of Four) teach people the art of design patterns and singletons in particular
- Singleton's have the reputation to not being thread-safe although recent Java releases would already counter that
- there's a way to implement a Singleton using enums
- generally, the advice of most people is to stay away of the Singleton pattern, at least how it's been implemented by the GoF or Hunter's code
- a Factory, yadp (yet another design pattern), can easily be used to return a single instance of a class, thus effectively making use of the pattern

Miyagi-san .. I mean, Wim

PS The GoF - Gang of Four - is a reference to the Head First Design Patterns book from O'Reilly. Well worth the read!
Wouter Oet
Saloon Keeper

Joined: Oct 25, 2008
Posts: 2700

Wim Vanni wrote:- Singleton's have the reputation to not being thread-safe although recent Java releases would already counter that

Could you explain that a bit further?

Wim Vanni wrote:PS The GoF - Gang of Four - is a reference to the Head First Design Patterns book from O'Reilly. Well worth the read!
Ehm no. The Gof are Erich Gamma, Richard Helm, Ralph Johnson & John M. Vlissides and is a reference to Design Patterns: Elements of Reusable Object-Oriented Software.
Mike Simmons
Ranch Hand

Joined: Mar 05, 2008
Posts: 3007
    
    9
Wouter Oet wrote:
Wim Vanni wrote:- Singleton's have the reputation to not being thread-safe although recent Java releases would already counter that

Could you explain that a bit further?

It sounds like a reference to the double-checked locking pattern for lazy instantiation, which was overly complex and yet fundamentally broken when it was first devised - since JDK 1.5 it has been possible to repair it, and also easier to avoid it entirely. That's what James Sabre and I were talking about above.

Thread safety can still be an issue if the singleton has mutable fields - just as for any other object. It's perhaps more of a concern for a singleton however, since we can't employ the often-useful technique of isolating mutable data to different threads. Singletons force all threads to use the same instance, so if the instance has mutable fields, it's much more likely that there will be threading problems if proper thread-safe techniques are used.
Wim Vanni
Ranch Hand

Joined: Apr 06, 2011
Posts: 96

Wouter Oet wrote:
Wim Vanni wrote:PS The GoF - Gang of Four - is a reference to the Head First Design Patterns book from O'Reilly. Well worth the read!
Ehm no. The Gof are Erich Gamma, Richard Helm, Ralph Johnson & John M. Vlissides and is a reference to Design Patterns: Elements of Reusable Object-Oriented Software.


I stand corrected
Mike Simmons
Ranch Hand

Joined: Mar 05, 2008
Posts: 3007
    
    9
Mike Simmons wrote:Singletons force all threads to use the same instance, so if the instance has mutable fields, it's much more likely that there will be threading problems if proper thread-safe techniques are used.

Oops. That should be:
Mike Simmons wrote:Singletons force all threads to use the same instance, so if the instance has mutable fields, it's much more likely that there will be threading problems unless proper thread-safe techniques are used.
Pat Farrell
Rancher

Joined: Aug 11, 2007
Posts: 4646
    
    5

Mike Simmons wrote:Singletons force all threads to use the same instance, so if the instance has mutable fields, it's much more likely that there will be threading problems unless proper thread-safe techniques are used.


Except, of course, when they don't.

The standard implementation, with examples all over the Internet, fails when there are multiple class loaders. In that case, you can have multiple instances of your "Singleton instance". This can help the thread safety stuff a little bit, but brings on many, many more issues.
Mike Simmons
Ranch Hand

Joined: Mar 05, 2008
Posts: 3007
    
    9
Well, yes, that's an example of when a singleton fails to actually be a singleton. It's one of the problems with singletons in Java, sure. But to the extent a singleton is actually a singleton, and if it has mutable data, it forces all threads to access that same mutable data - that's all I was addressing.
Pat Farrell
Rancher

Joined: Aug 11, 2007
Posts: 4646
    
    5

So, in summary so far, the Singleton pattern is great except:

  • to the extent a singleton is actually a singleton, and if it has mutable data, it forces all threads to access that same mutable data
  • It is not a singleton in cases where there are two or more class loaders
  • The simple implementation is subject to the double-lock falicy flaw
  • It makes proper unit testing impossible
  • it increases coupling between modules or packages
  • it decreases cohesion within a module or package
  • There are alternatives that solve these problems that are as easy to use
  • Its grossly overused by beginning Java programmers
  •  
    I agree. Here's the link: http://aspose.com/file-tools
     
    subject: Singleton pattern