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

singleton objects?

Rajendra Deshpande
Ranch Hand

Joined: Nov 24, 2000
Posts: 40
Hi,
Could someone explain what a Singleton object is, its uses and pecularities if any.
thanks in anticiption of reply.
deekasha gunwant
Ranch Hand

Joined: May 06, 2000
Posts: 396
Hi Rajendra,
Singleton class is a class whose only one object can be created at a time.
To achieve this one method is that we make it's constructor private and provide a static method that returns it's instance. here is a code.

e.g. Runtime is a Singleton class in Java Library.
run the above code hope u'll understand the concept
regards
Deekasha
Rajendra Deshpande
Ranch Hand

Joined: Nov 24, 2000
Posts: 40
Deekasha,
Thanks for the reply. However, thats too much of a code for a novice like me. Could you be kind to explain the purpose of a 'private constructor'.
thanks,
Rajendra.
Frank Carver
Sheriff

Joined: Jan 07, 1999
Posts: 6920
A singleton is an object of which there may only ever be a single instance. (*)
You can make your own class act like a singleton, simply by only creating a single instance. But this relies on every programmer who uses your code knowing that there is only supposed to be one instance of the class, which is dangerous. A better solution is to write the class in a way which prevents a casual programmer from creating more than one instance. This is where the Singleton pattern and its associated Java idioms help you.
Lets start with a simple class:

The most obvious way for a programmer to try to create an instance of a class is to call its constructor, so we need to prevent this. If we just fail to provide a constructor, Java assumes that there is a "default constructor" taking no arguments which just creates an instance of the class; not what we need! The Java "trick" for this is to have a constructor, but make it private so no other classes may call it.

Now that we have no constructor, we need to make a way for people to create a single instance of the class. Typically this is done by provding a static method which creates an instance, but will create only one. If it is called again, it just returns the same instance that it created the first time.

Now the code is almost complete. The last thing to remember is that Java is a multi-threaded language in which many things can be happening "at once". If two threads were to call getInstance at the same time, then our class might occasionally create two instances, which would be wrong and very hard to test. So we make use of Java's built-in synchronization mechanism to make sure that only one thread can call getInstance at any one time.
So the final singleton class looks like:

I hope this helps.

(*) The Singleton pattern actually allows for a specified number of instances, but singletons are harly ever used for any number other than one.


Read about me at frankcarver.me ~ Raspberry Alpha Omega ~ Frank's Punchbarrel Blog
Rajendra Deshpande
Ranch Hand

Joined: Nov 24, 2000
Posts: 40
Hi Frank Carver,
Thanks a lot. There cannot be a more clear and insightful explanation. You have been a great help.
-rajendra.
bill bozeman
Ranch Hand

Joined: Jun 30, 2000
Posts: 1070
Great Post Frank. Really explained it great.
Bill
David Yutzy
tumbleweed and gunslinger
Ranch Hand

Joined: Jun 29, 2001
Posts: 192
I have a question about this subject...
Currently, we have an application were we have DAO objects where the methods are static and Eclipse/PMD is complaining about using a singlton.
Our current usage is simple:

From your description of a singleton, as I understand, we would have to change the code to use the .getInstance() method such as:

If so, this would really suck having to go through all objects/methods and actually create an instance of the DAO to use it.
What are the benefits of using singleton vs. all static methods? Now that I understand how to create one, I really don't see the benefit, rather, it seems worse to have to actually create an instance before usage...
...or maybe I just missed the boat when they were handing out singletons...
[ June 27, 2003: Message edited by: David Yutzy ]
John Smith
Ranch Hand

Joined: Oct 08, 2001
Posts: 2937
What are the benefits of using singleton vs. all static methods? Now that I understand how to create one, I really don't see the benefit, rather, it seems worse to have to actually create an instance before usage...
A class with all static methods is considered a pure utility class and as such is much less flexible than the Singleton. It's tempting to overuse the classes with all static methods, especially if you have a procedural programming background, not realizing that it breaks the OOP paradigm.
Unlike the class with all static data, you can subclass the Singleton and override its methods. It may also be easier to maintain state in the Singleton. The Singleton can also implement interfaces in a meaningful way. In addition, you can control the number of instances (for example, you may want to have one instance of the class per thread).
Finally, it's worth pointing out that both Singleton and the classes with all static methods are frequently abused. Before you write a Singleton or its equivalent, think carefully, -- should your class really be a singleton? Will it be the singleton if your requirements change or if you simply want to modify a particular part of your program? In many cases, you would realize that a better design would be not to put a constrain on your class, -- that will allow it to evolve easier.
Eugene.
David Weitzman
Ranch Hand

Joined: Jul 27, 2001
Posts: 1365
What are the benefits of using singleton vs. all static methods?
If a class is going to have any state or needs to implement a certain interface, go with a Singleton. For plain old utility classes, static methods are just fine.

From your description of a singleton, as I understand, we would have to change the code to use the .getInstance() method such as:
(code omitted)
If so, this would really suck having to go through all objects/methods and actually create an instance of the DAO to use it.

If you're using Eclipse, you can mostly automate the transition with the refactoring features.
First, create a getInstance() method and implement it.

Next use "Extract Method" to move the contents of each utility method into a different method and delegate any calls to the new method:

Here's the part you'll have to so yourself. Make all the newly extracted methods non-static.

Then updating all of your code to use the singleton is simply a matter of using Eclipse's automated "Inline" refactoring on the static methods.
David Yutzy
tumbleweed and gunslinger
Ranch Hand

Joined: Jun 29, 2001
Posts: 192
The only time I've found that Eclipse complains about the "singleton" is in my DAO classes, which typically just call a Stored Procedure or execute some specialized Prepared Statements.
I've found there is no real need / benefit to extend or implement such classes as they are very specific to the project and highly customized.
These classes, however, do extend two other classes I've created called Database and jdbcConnection which service connections and other database specific functionality. Both of these sound like candidates for Singleton, but the DAO's do not.
Thank again to everyone for the info. It really cleared out the cobwebs!
Anonymous
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
Hi all:
First, what an answer of the sheriff!. Well, I have an annoying (is that a word?) custom to try to compile any code that I see, so I have to report the error:
this.contemt = content;
Undefined symbol contemt.
Anyway, the purpose of the post is to congratulate the sheriff for the Singleton explanation and to remind to David Yutzy that a DAO will not allways be relying on a RDBMS (it could be a file or better a legacy system), so not allways the jdbc connections will be the way to connect.
Please excuse my english and best regards to all.
chandana sapparapu
Ranch Hand

Joined: Sep 28, 2002
Posts: 63
Unlike the class with all static data, you can subclass the Singleton and override its methods. It may also be easier to maintain state in the Singleton. The Singleton can also implement interfaces in a meaningful way. In addition, you can control the number of instances (for example, you may want to have one instance of the class per thread).


I could subclass a class with all static methods and fields. I could override these static methods in the base class. I don't know what you really mean.

Thanks,
Chandana
Maulin Vasavada
Ranch Hand

Joined: Nov 04, 2001
Posts: 1871
Originally posted by chandana sapparapu:

I could subclass a class with all static methods and fields. I could override these static methods in the base class. I don't know what you really mean.

Thanks,
Chandana


Well, if we break your sentence into two parts,
1. I could subclass a class with all static methods and fields
2. I could override these static methods in the base class

1st one is right.
2nd one is wrong.

And thats why you got confused We can't "override" static methods. Static methods can only be shadowed. This means that see the following example,



Output
------
A.print()
A.print()
B.print()

Hopefully this explains it.

Thanks
Maulin
chandana sapparapu
Ranch Hand

Joined: Sep 28, 2002
Posts: 63
Thanks Maulin. Great explanation. In my example, I just tried Case 3 and it worked. It didn't occur to me to test case 2.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: singleton objects?
 
Similar Threads
Hashtable's put method problem in locking
singleton class
Tech Word Game
Creating a utility managed bean, to move common code and use from different beans?
Single pattern