• 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:
  • Tim Cooke
  • Campbell Ritchie
  • paul wheaton
  • Ron McLeod
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Piet Souris
Bartenders:

singleton vs static methods

 
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
what are the benefits of the singleton pattern over a class with static methods?
 
Ranch Hand
Posts: 1551
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
A Singleton can allow access to many instances, a pooling scheme.
 
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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.
 
Ranch Hand
Posts: 1871
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.....
 
Ranch Hand
Posts: 2713
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
Posts: 12
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator


>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.
 
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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?
 
Ranch Hand
Posts: 1011
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Read this article and you will get a much clearer picture about singleton:
http://developer.java.sun.com/developer/technicalArticles/Programming/singletons/
 
Ranch Hand
Posts: 313
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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,
 
Vitaliy Shevchuk
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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.
 
Ranch Hand
Posts: 925
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
author
Posts: 14112
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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?
 
SJ Adnams
Ranch Hand
Posts: 925
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
Posts: 12
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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.
 
Ranch Hand
Posts: 1365
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
Posts: 925
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
if anyone is still interested in the difference between 1.3 and 1.4 I've posted the comparison to
https://coderanch.com/t/201812/Performance/java/Making-everything-compiler-allows-final
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic