permaculture playing cards*
The moose likes Architect Certification (SCEA/OCMJEA) and the fly likes singleton vs static methods Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCA/OCP Java SE 7 Programmer I & II Study Guide this week in the OCPJP forum!
JavaRanch » Java Forums » Certification » Architect Certification (SCEA/OCMJEA)
Bookmark "singleton vs static methods" Watch "singleton vs static methods" New topic
Author

singleton vs static methods

tom walters
Ranch Hand

Joined: Feb 14, 2002
Posts: 34
what are the benefits of the singleton pattern over a class with static methods?
Rufus BugleWeed
Ranch Hand

Joined: Feb 22, 2002
Posts: 1551
A Singleton can allow access to many instances, a pooling scheme.
Vitaliy Shevchuk
Greenhorn

Joined: Aug 21, 2002
Posts: 12
Originally posted by Rufus Bugleweed:
A Singleton can allow access to many instances, a pooling scheme.

Also, static methods invocation is MUCH faster. (Sometimes you need performance, as well) But I recoment to forget this point untill you complete your architect certification, as static methods will not be appresiated here
Vit.


----------<br />creator of AjaxAnywhere, SCEA, SCBCD, SCWCD<br /><a href="http://ajaxanywhere.sourceforge.net" target="_blank" rel="nofollow">http://ajaxanywhere.sourceforge.net</a>
Rahul Mahindrakar
Ranch Hand

Joined: Jul 28, 2000
Posts: 1851
A good question indeed and should be thought about by every individual before deciding on whether to use singletons or static methods.
But Rufus has stated the correct answer and I am still thinking...
Hmmmmm.....
Chris Mathews
Ranch Hand

Joined: Jul 18, 2001
Posts: 2712
The Singleton pattern:
1) Hides instance initialization.
2) Guarantees a single instance of the object in memory and can be changed later to allow multiple instances if necessary. Static methods cannot address this at all.
3) Allows the developer to take advantage of inheritance by extending classes or implementing interfaces and allowing one's singleton to be subclassed, thus the interface can be separated from the implementation (00P 101). Static methods cannot not be inherited in Java.
4) Allows lazy initialization. Object will not be instantiated until first use. The static method approach puts you at the mercy of the classloader for object instantiation.
5) Singletons can be serialized to save state if necessary.
I don't buy the static methods are faster approach. Singletons aren't going to be a performance problem unless you are doing real-time systems (in which case you are more worried about gc). Come on, the bottleneck is going to be database access, network calls, monolithic servlets, fine-grained entity beans, or some other far reaching problem. If you are creating a large-scale J2EE application then Singletons are going to be your last worry as far as performance goes.
Vitaliy Shevchuk
Greenhorn

Joined: Aug 21, 2002
Posts: 12

>Come on, the bottleneck is going to be database access, network calls, monolithic servlets, fine-grained entity beans, or some other far reaching problem. If you are creating a large-scale J2EE application then Singletons are going to be your last worry as far as performance goes.

Well, in every solutions there are advantages and disadvantages. You are rignt, but the issue of performance is much more important then you think. Imagine, you have a code like this:
for (... i<100000)
for (... j<10000)
myMethodInvocation()
In this case Singelton is too slow. Non-private method invocation (without parameters) is almost 2 times slower then static and/or private.
Again, everybody knows the advantages, but nobody takes care of disadvantages.
Vit.
Redding
Greenhorn

Joined: Aug 21, 2002
Posts: 6
I've always wandered about the Singleton patern. It's not clear to me how it couldn't be a bottle-neck in some situations. If there are many objects in a system that need to simultaneously make calls to a method in a single instance, wouldn't each of the calls have to wait their turn to get access to the singleton object? Is that not a real issue to consider when deciding on a design?
Tong Chen
Ranch Hand

Joined: Apr 26, 2002
Posts: 1011
Read this article and you will get a much clearer picture about singleton:
http://developer.java.sun.com/developer/technicalArticles/Programming/singletons/


Tong Chen (Seattle USA)<br />SCJP,SCWCD,SCDJWS,IBM XML,MCP.NET,MCAD.NET,MCSD.NET
Byron Estes
Ranch Hand

Joined: Feb 21, 2002
Posts: 313
There's another point that I haven't seen addressed...
For the use of a static/class level object to work it must complete it's behavior in a single method call, or a series of static calls where values are only passed in via parameters or the member variables used are static too.
A singleton takes a different approach and is not restricted to using only static methods, static member variables and passed in parameters.
Each has it's use, each has benefits and each has it's own problems. I don't see it as an either/or. It's like they are two screwdrivers, ones a torx and the other is a phillips head. You might be able to get the other one to remove any given screw, but it's easier if you use the one designed to remove that type of screw.
I've used both singletons and static classes in my software designs. I find that I use static classes more frequently.
Regards,


Byron Estes<br />Sun Certified Enterprise Architect<br />Senior Consulant<br />Blackwell Consulting Services<br />Chicago, IL<br /><a href="http://www.bcsinc.com" target="_blank" rel="nofollow">www.bcsinc.com</a>
Vitaliy Shevchuk
Greenhorn

Joined: Aug 21, 2002
Posts: 12
Originally posted by shyh:
I did a simple test investigating the performance of calling static/nonstatic, public/private methods with a loop of 1,000,000 times, and the results are the same.
So, I don't get your points.
Do you mean by "calling multiple times of a nonstatic method of one single instance", or "calling the nonstatic method of multiple new instances"?

I'm sure you mised something in your Investigation
try this:
public class C{
static int i;
private static void a(){
i++;
}
public void b(){
i++;
}
public static void main(String[] args) throws Exception{
C c = new C();
long l = System.currentTimeMillis();
for(int i=0;i<100000;i++){
for (int j=0;j<10000;j++){
a();
}
}
System.out.println( System.currentTimeMillis() - l);
l = System.currentTimeMillis();
for(int i=0;i<100000;i++)
for (int j=0;j<10000;j++){
c.b();
}
System.out.println( System.currentTimeMillis() - l);
}
}
----------------------
I got the following:
5015
10735
Good luck.
Vit.
SJ Adnams
Ranch Hand

Joined: Sep 28, 2001
Posts: 925
Erhermm....
Thats more because the static method is treated as final, behold:
public class C{
static int i;
private static void a(){
i++;
}
public void b(){
i++;
}

public final void c(){
i++;
}
public static void main(String[] args) throws Exception{
C c = new C();
long l = System.currentTimeMillis();
for(int i=0;i<100000;i++){
for (int j=0;j<10000;j++){
a();
}
}
System.out.println( System.currentTimeMillis() - l);
l = System.currentTimeMillis();
for(int i=0;i<100000;i++)
for (int j=0;j<10000;j++){
c.b();
}
System.out.println( System.currentTimeMillis() - l);
l = System.currentTimeMillis();
for(int i=0;i<100000;i++)
for (int j=0;j<10000;j++){
c.c();
}
System.out.println( System.currentTimeMillis() - l);
}
}
The results:
C:\>java C
5281
11406
4719
C:\>
Good luck indeed.
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
Originally posted by Simon Lee:
5281
11406
4719

Interesting - here is what I got, using JDK 1.4.1-beta on Windows 2000:
12658
12648
13940
What JVM did you use?


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
SJ Adnams
Ranch Hand

Joined: Sep 28, 2001
Posts: 925
P:\>java -version
java version "1.3.1_03"
Java(TM) 2 Runtime Environment, Standard Edition (build 1.3.1_03-b03)
Java HotSpot(TM) Client VM (build 1.3.1_03-b03, mixed mode)
Vitaliy Shevchuk
Greenhorn

Joined: Aug 21, 2002
Posts: 12
Originally posted by sh yh:
Mmm...
So, I guess the performance for static and non-static methods depends on how the JVM is implemented. However, it does not matter whether the method is "public" or "private".

Yes, looks like the results we got depend on ByteCode->Native compilation and run-time optimization of JVM. As we can see, SUN make progres in this field.
However, static method invocation is translated into a single ByteCode command: "invokestsatic", but non-static method invocation is translated into 2 commands: "aload" and "invokevirtual". First JVM pushes object reference to stack, then it invokes a method on the object. For private methods JVM still uses 2 commands: "aload" and "invokespecial".
The results shown by jvm1.4 are amazing. I see no reasons to use static methods instead of singelton any more. Well done, SUN .
Vit.
David Weitzman
Ranch Hand

Joined: Jul 27, 2001
Posts: 1365
Here's something singleton did for me:
I recentlly wrote a typical object registry. There's a .properties file that has a bunch of records in the general form 'EAT=command.EatCommand'. There are many threads accessing the commands at once, and I wanted to insure that each commands gets created only once and shared (I suppose I could have made all the commands singletons, but tthe reflection calls would be ugly and the classes would be difficult to maintain).
I originally wrote the registry with nothing but static methods. There was a static code block for loading the commands, so the commands were only created once the way I wanted it. It had a big problem though -- loading the commands leaves plenty of room for exceptions, but they would just be ignored if they happened in a static block. Plus I needed to log any exceptions to a specific instance of a logger that it couldn't access.
I switched to a singleton, where I had a method with a descriptor something like this:
public static CommandRegistry getInstance(Logger log) throws ConfigurationException
The new problem then was that I was dealing with configuration exceptions in any part of my program that wanted to access the registry -- even long after configuration ought to be over. My solution to this was something you can't do with static methods: I decided to create the instance of CommandRegistry early in the program and pass it around.
The simple fact that Singletons are objects is extremely useful. They can be passed around to code that doesn't care that they're singletons as long as they have certain methods.
By the way, another interesting pattern is monostate
SJ Adnams
Ranch Hand

Joined: Sep 28, 2001
Posts: 925
if anyone is still interested in the difference between 1.3 and 1.4 I've posted the comparison to
http://www.coderanch.com/t/201812/Performance/java/Making-everything-compiler-allows-final
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: singleton vs static methods