It's not a secret anymore!*
The moose likes OO, Patterns, UML and Refactoring and the fly likes Singleton Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Engineering » OO, Patterns, UML and Refactoring
Bookmark "Singleton " Watch "Singleton " New topic
Author

Singleton

anne lai
Greenhorn

Joined: Sep 22, 2001
Posts: 8
Hi there,
I have some questions about the singleton pattern, we all use it to implement the database connections pooling. But singleton is to allow only one instance of your class, database connections-pool should allow many connections. Why and how we handle it here? what are the disadvandges of singleton patern, how does this book address this pattern?
thanks,
anne
Farouk Mohamed1
Ranch Hand

Joined: Jul 26, 2001
Posts: 113
Hi anne
Singleton pattern is right according to what you said, it is useful to create only one instance of a Object.
Singleton's Usage in Connection Pooling:
1.Usually a Connection Manager will be created as a singleton object.
2. Connection Manager will hold multiple connections of connections and as well sometimes encapsulates the responsibilities of managing a connection and providing a connection.
3. By creating a connection manager object the control of all connections are through this manager,so there is unity of command enforced by the manager an no misuse of database connections possible by other means
Please reply to this if you are not clear any more?
Farouk
Yoo-Jin Lee
Ranch Hand

Joined: Nov 01, 2000
Posts: 119
Hi Anne,
The simplest way to create a singleton pattern is as follows:
<code>
public class MySingleton{
private static MySingleton myInstance = new MySingleton();
private MySingleton(){}
public static MySingleton getInstance(){
if (myInstance == null) {
myInstance = new MySingleton();
}
return myInstance;
}
}
</code>
So by making the only possible constructor private you have to use the public static and final method getInstance() to get an instance of MySingleton. The field myInstance is static so that there can only be one instance of it. This is the basis of a connection manager.
Now you can see how a real pool manager works by examining a real world connection manager at poolman.
Hope this helps.
Yoo-Jin
[This message has been edited by Yoo-Jin Lee (edited October 02, 2001).]
Alan Shalloway
Ranch Hand

Joined: Sep 26, 2001
Posts: 60
The responses here said it well, so I won't describe singleton, but I will mention a couple of challenges with it.
First of all, Singleton only works in single-threaded applications. There is a pattern that works for multi-threaded applications called double checked locking that is pretty simple (See Pattern Oriented Software Architecture Vol 1). Unfortunately, the JVM has a bug in how it handles multi-threading and instantiation and Double Checked Locking (DCL) doesn't work properly. There is actually some contention over here as to who is at fault. Some claim DCL is trying to trick the JVM and it's not the JVM's fault, others claim there is a bug in the JVM. I haven't investigated this enough to determine where the fault lies. However, I do know this:
use singleton only in single threaded systems, and DCL doesn't work properly under Java.
------------------
Alan Shalloway,
Look for Jim Trott and my book: Design Patterns Explained
Visit our site Net Objectives.
Visit our on-line companion to the book


Alan Shalloway.<BR>Look for Jim Trott and my book: <A HREF="http://www.amazon.com/exec/obidos/ASIN/0201715945/ref=ase_electricporkchop/103-0514572-3811868" TARGET=_blank rel="nofollow">Design Patterns Explained</A><BR>Visit our site <A HREF="http://www.netobjectives.com" TARGET=_blank rel="nofollow">Net Objectives</A>.<BR>Visit our <A HREF="http://www.netobjectives.com/dpexplained/index.html" TARGET=_blank rel="nofollow">Design Patterns Explained Community of Practice</A><BR>Check out our <A HREF="http://www.netobjectives.com/xml/xml_cdrom_info.htm" TARGET=_blank rel="nofollow">CDROM based audio training in XML</A>
Burkhardt Hufnagel
Greenhorn

Joined: May 08, 2001
Posts: 14
I disagree with the idea that Singletons only work in a single-threaded environment. I've read several articles on Double Lock Checking and how it doesn't work so I understand the concern, but that doesn't mean that you are restricted to one thread when using a Singleton.
What if you do something like this:
class OnlyOne {
static private OnlyOne myInstance;
static {
myInstance = new OnlyOne();
}
private OnlyOne() {
}
public void usefulMethod() {
}
}
As I understand it, a static initializer will only execute once - when the class is loaded.
Wouldn't this work?

TANSTAAFL
Burkhardt Hufnagel
Greenhorn

Joined: May 08, 2001
Posts: 14
Whoops! Forgot the getInstance() method.
class OnlyOne {
static private OnlyOne myInstance;
static {
myInstance = new OnlyOne();
}
private OnlyOne() {
}
public static OnlyOne getInstance() {
return myInstance;
}
public void usefulMethod() {
}
}
John Dale
Ranch Hand

Joined: Feb 22, 2001
Posts: 399
It appears that when Alan says to "use singleton only in single-thread systems", he is referring to implementing the singleton with lazy initialization, and to attempting to avoid synchronization by using double-checked locking.
Indeed, it is well documented that double-checked locking is broken. See the "Double-Checked Locking is Broken" Declaration at http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html
However, there are several thread-safe approaches to implementing singleton. The simplest is the static initializer (as explained by Burkhardt above).
<code>
class SingletonA {
// to implmement singleton
private static SingletonA instance = new SingletonA();
public static SingletonA getInstance() {
return instance;
}
private SingletonA() { }
// other members go here
}
</code>
If you cannot use a load-time initializer, you can use lazy initialization protected for multiple threads.
<code>
class SingletonB {
// to implmement singleton
private static SingletonB;
public static synchronized SingletonB getInstance() {
if (instance == null)
instance = new SingletonB();
return instance;
}
private SingletonB() {}
// other members go here
}
</code>
This issue is discussed in Joshua Bloch's Effective Java Programming Language Guide (item 48), including both of the above approaches, and the additional alternative of initialization on demand using a holder class.
You can also use ThreadLocal with lazy initialization to eliminate the need to run synchronized code with each getInstance() call. I think this may be described in the DCL is broken declaration above.
By the way, Alan's book, Design Patterns Explained, is great. I and about half a dozen co-workers read it. I think everybody liked it and thought it was worthwhile. The only wart that comes to mind is the one or two page discussion of double-checked locking.
[Edited 10/04 to show that the constructor must be private, as pointed out in comments by others. -jd]
[This message has been edited by John Dale (edited October 04, 2001).]
Pho Tek
Ranch Hand

Joined: Nov 05, 2000
Posts: 761

I noticed an implementation of a singleton class
that doesn't have any constructor definition. Java
will add a public no-arg constructor of course - but
is this a violation of the pattern per se ?
Pho


Regards,

Pho
Alan Shalloway
Ranch Hand

Joined: Sep 26, 2001
Posts: 60
Originally posted by Pho Tek:
I noticed an implementation of a singleton class
that doesn't have any constructor definition. Java
will add a public no-arg constructor of course - but
is this a violation of the pattern per se ?
Pho

When using Singleton it is very important to define the constructor as protected or private. Otherwise, people will be able to instantiate objects of the singleton type which is what you are trying to avoid.

------------------
Alan Shalloway,
Look for Jim Trott and my book: Design Patterns Explained
Visit our site Net Objectives.
Visit our on-line companion to the book
Andrew Ao
Greenhorn

Joined: Sep 10, 2001
Posts: 16
why do we usually suggest using lazy loading in java? shouldn't it just work the same by instantiating in a static field.
-aao
Andrew Ao
Greenhorn

Joined: Sep 10, 2001
Posts: 16
I also think that it would be simpler and more efficient to use a static field than lazy loading.
-aao
John Dale
Ranch Hand

Joined: Feb 22, 2001
Posts: 399
Sometimes creating the instance at load time won't work, so we have to use other techniques.
Desai Sandeep
Ranch Hand

Joined: Apr 02, 2001
Posts: 1157
Hi Anne,
I have used Singleton pattern, when I wanted only one global instance of class to be shared by all the objects.
I needed to use this pattern when I developed an AddressBook application sometime back.It contained all the addresses of the employees in an XML format.Now cosider the client creating a new instance of the AddressBook and writing the address in the ML file.The result would be all the previously stored addresses in the previous Addressbook XML file would be lost.
To avoid this to happen, I had to see that only one instance of AddressBook has to be given to the clients.Hence, I designed the AddressBook class using Singleton Pattern.
If you compare this wih Connection Pooling, you will realize that Singleton Pattern is actually not applicable in this case.The stress is not on giving the same Connection object to the client, but to limit the connections (depending on the estimate of web traffic), so that connection time and hence performance is improved.
Hope this helps,
Sandeep


<b>Sandeep</b> <br /> <br /><b>Sun Certified Programmer for Java 2 Platform</b><br /> <br /><b>Oracle Certified Solution Developer - JDeveloper</b><br /><b>-- Oracle JDeveloper Rel. 3.0 - Develop Database Applications with Java </b><br /><b>-- Object-Oriented Analysis and Design with UML</b><br /> <br /><b>Oracle Certified Enterprise Developer - Oracle Internet Platform</b><br /><b>-- Enterprise Connectivity with J2EE </b><br /><b>-- Enterprise Development on the Oracle Internet Platform </b>
anne lai
Greenhorn

Joined: Sep 22, 2001
Posts: 8
Originally posted by John Dale:
Sometimes creating the instance at load time won't work, so we have to use other techniques.

Thank you guys! It does help me a lot.
Do you think both Singleton implementations (to make the class instance as static field and initialize the Singleton lazily) will cause some inconvience when subclassing?
-Anne
ruilin yang
Ranch Hand

Joined: Feb 25, 2001
Posts: 334
Some book indicated that the sigleton pattern allows a variable number of instances and it is more flexible than static methods.
I am confused with this statement. I thought the sigleton pattern only permit a single instance.
Please help.
Thanks
Ruilin
Andrew Ao
Greenhorn

Joined: Sep 10, 2001
Posts: 16
Originally posted by John Dale:
Sometimes creating the instance at load time won't work, so we have to use other techniques.

i guess i didn't make it very clear.
1) the classloader load class when Singleton.newInstance().
2) only at that time of class loading, the static field would be initialized.
therefore, i considered it would work the same as "double-check for lazy loading" while removing the overhead of synchronization.
please comment if there is a fault with my understanding.
regards,
-aao
John Dale
Ranch Hand

Joined: Feb 22, 2001
Posts: 399
It seems plausible that you might have a singleton class with some static elements that need to be used before the class is instantiated. However, I've don't recall running across such a situation in practice.
The point is that "double-check for lazy loading" should never be used, since it is not safe. The simple static initializer (e.g., SingletonA above) is safe, and often sufficient. If you have a situation in which it won't work, use an appropriate safe alternative.
[This message has been edited by John Dale (edited October 07, 2001).]
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
Originally posted by ruilin yang:
Some book indicated that the sigleton pattern allows a variable number of instances and it is more flexible than static methods.
I am confused with this statement. I thought the sigleton pattern only permit a single instance.

The Singleton pattern encapsulates the design decision of only having one instance. If you later decide you need two instances instead, you don't habe to change any clients.
For more interesting discussion on the Singleton pattern, see http://c2.com/cgi-bin/wiki?SingletonPattern


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
Yoo-Jin Lee
Ranch Hand

Joined: Nov 01, 2000
Posts: 119
Hi Ruilin,
You can control the number of instances a singleton class can generate as so:
<code>
public class MySingleton{
private static MySingleton [] myInstances = [new MySingleton(),new MySingleton()];
private MySingleton(){}
public static MySingleton getInstance(){
if (myInstances[0] == null) {
myInstances[0] = new MySingleton();
return myInstances[0];
} else {
if (myInstances[1] == null) {
myInstances[1] = new MySingleton();
}
return myInstances[1];
}
}
}
</code>
Take note, that this is horrible code it but it'll give you a better idea of controlling the number of instances. Here we see that the getInstance() method controls the number of instances of MySingleton that are returned. You could develop add a check-out system and have your own connection/object manager.
Hope this helps.
-Yoo-Jin
 
GeeCON Prague 2014
 
subject: Singleton