• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Singleton pattern

 
Ranch Hand
Posts: 635
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
[/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?
 
Java Cowboy
Posts: 16084
88
Android Scala IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
Ranch Hand
Posts: 492
Firefox Browser VI Editor Linux
  • Likes 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
 
Jesper de Jong
Java Cowboy
Posts: 16084
88
Android Scala IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
Posts: 492
Firefox Browser VI Editor Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I didn't see any mention of threads above so I posted the simplest example I could think of.


Hunter
 
Ranch Hand
Posts: 781
Netbeans IDE Ubuntu Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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 ?
 
Master Rancher
Posts: 4796
72
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
Posts: 781
Netbeans IDE Ubuntu Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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
Master Rancher
Posts: 4796
72
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
A good overview with links to more detailed materials: Java Memory Model.
 
Ranch Hand
Posts: 1376
Eclipse IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

@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
Posts: 635
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Is using a private constructor the only way in order to create singleton pattern?
 
Mike Simmons
Master Rancher
Posts: 4796
72
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Considering that I've already shown another way above, the answer would be no.
 
Rancher
Posts: 4803
7
Mac OS X VI Editor Linux
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
Bartender
Posts: 2700
IntelliJ IDE Opera
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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.
 
Pat Farrell
Rancher
Posts: 4803
7
Mac OS X VI Editor Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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.
 
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
Posts: 4803
7
Mac OS X VI Editor Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
Posts: 492
Firefox Browser VI Editor Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
Posts: 4803
7
Mac OS X VI Editor Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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
Bartender
Posts: 2700
IntelliJ IDE Opera
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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.
 
Ranch Hand
Posts: 96
Eclipse IDE Oracle Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
Bartender
Posts: 2700
IntelliJ IDE Opera
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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
Master Rancher
Posts: 4796
72
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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
Posts: 96
Eclipse IDE Oracle Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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
Master Rancher
Posts: 4796
72
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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
Posts: 4803
7
Mac OS X VI Editor Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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
Master Rancher
Posts: 4796
72
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
Posts: 4803
7
Mac OS X VI Editor Linux
  • Likes 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
  •  
    reply
      Bookmark Topic Watch Topic
    • New Topic