This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Difference between static class and singleton pattern?
I was wondering,
Would a class such as Java's Math class, where all methods are static be considered a singleton? Or does a singleton have to have an instance, eg: Math.getInstance().abs(...) to qualify as a singleton?
Thanks
Having just static methods in a class does not qualify it being a Singleton, as you can still make as many instances of that class, if you have a public constructor in it.
For a class to qualify as Singleton, it should have private constructor, so that it can't be instantiated from outside the class, and have a static factory that returns the same instance everytime invoked.
If you really mean static class, then first of all, you can't have your top-level class as static. You can only have static nested class, in which case you don't need to create any instance of that class, but you can and you can create multiple instances and hence it as not Singleton.
Also, the class you mentioned - java.lang.Math, is not a static class. You should see the documentation of that.
Static classes in Java are just nested classes which aren't inner classes. (They're not like static classes in C#, for example.) They can still have instance methods, state etc - and there can be multiple instances.
java.lang.Math is not a static class.
And no, a class which never has an instance is not a singleton. The important difference is that a singleton can implement an interface (or even derive from an abstract class) whereas if you never create an instance of a class, any instance methods are pointless.
A class that is applied Singleton Pattern has one or none instance at any time on a JVM. That's why it's called single-ton. Having static or non-static members has no relationship with being singleton or non-singleton.
Static classes usually provide some helper methods. In fact i don't think its appropriate to compare Static classes with Singleton. Both are completely different.
We can create multiple instances of a static class but singleton guarantees(atleast in theory) only single instance.
It would have to have an instance with Singleton meaning to only be initialised, once.
Edit: Here's a link to the Wikipedia article
A singleton guarantees that there is only up to one instance of that class within the environment. It is different from a class with a bunch of static methods. A singleton carries state and can carry runtime values, while static methods of a class don't.
You can argue that you can have static values to do that, but the purpose of static variables is different (and sometimes abused like global variables). So a singleton operates in a different context than static methods.
A singleton also is usually associated with some resource (some connection to another server, access to some file, etc.) for which a static instance wouldn't be that ideal. Singletons also allow for lazy loading (if connecting or accessing a resource is expensive), while classes get loaded when the classloader encounters a reference to them.
Related
I'm wondering what different between static method and singleton class method when i use them for multiple thread. I think if use static method, it will conflict result data or parameter but i don't think use singleton method class then the same problem will occur.
We use "synchronized" to solve the multiple threads problem.
The static method and singleton method's main differences are:
1. a static method can only use the static fields and methods, as a non-static method can use all fields and methods of the class.
2. a static method can be called without a instance, as a non-static method must be called by a instance.
When you create a static method it can be used without creating an instance of the class, which is not true when you're creating a class-method.
Synchronization is orthogonal issue: you'll probably have to use some kind of synchronization mechanism regardless of which one of the two options you chose to use.
If I define a class which is full of static member function and variable(java), then something interesting may happen.
Can I use the class as a single instance of the class and have no need worrying about conveying the instance variable?
How will the construction function take effect if I don't instantiate an object? So I can't initialize the static member variable in construction function, right?
If I define a class which are full of static member function and variable(java), then something interesting may happen.
Not really, usually helper / utility classes don't have instance level fields.They only have static methods and static fields.
Can I use the class as a single instance of the class and have no need worrying about conveying the instance variable
No, marking all methods and fields as static won't make this a Singleton class.
How will the construction function take effect if I don't instantiate an object
The default constructor will be called when you do new MyClass().
So I can't initialize the static member variable in construction function, right?
You can. Unless it is marked as final. You might run into trouble if you have static blocks
It is working same as any other class with static members, no matter if all of them are static or only part of them. They are used as expected - bound to class, not to instance.
Also you can actually have "static class" with constructor, look for Singleton pattern (however be aware, that pattern can be misused very easily).
Do Java classes have an instance on machine (JVM) level if they contain only static methods and fields?
And if yes, what are the effects of static methods and fields when doing multithreading? Any rules of thumb?
Yes, for each loaded class in the JVM there is an instance of java.lang.Class. It does not matter whether they only contain static methods/fields or instance methods/fields as well.
And this does not have any extra impact on multi-threading beyond what instance fields and methods already have. That is, as long as you realise that the value of a static field is shared between all instances.
If you want to synchronize, you need to synchronize on the java.lang.Class instance for the class (or if the method is a static method inside said class, it can have the 'synchronized' modifier on the static method to have the same effect as synchronizing on the java.lang.Class instance for the class).
One extra thing to note is that a class with the same name can be loaded by more than one classloader at the same time in the JVM- hence classes in Java are not uniquely identifier by their fully-qualified name, instead they are uniquely identifier by the combination of java.lang.ClassLoader instance used to load the class, and the fully-qualified name.
Static methods and variables are at the class level in Java, not instance level.
All shared, writable state needs to be synchronized and thread safe, regardless of static or instance.
There are no such thing as "static classes" in java. There are inner static classes, but i presume that your question its not about this type of classes.
Classes are loaded once per classloader not per Virtual Machine, this is an important diference, for example applications server like tomcat have different classloaders per application deployed, this way each application is independent (not completely independent, but better than nothing).
The effects for multithreading are the effects of shared data structures in multithreading, nothing special in java. There are a lot of books in this subject like http://www.amazon.com/Java-Concurrency-Practice-Brian-Goetz/dp/0321349601 (centered in java) or http://pragprog.com/book/pb7con/seven-concurrency-models-in-seven-weeks (that explain difference concurrency models, really interesting book)
Yes, a class with static fields and methods has exactly one instance, which is accessed through a static call.
If you use static methods, the variables declared within the method are isolated and don't need to be synchronized (the same as in C#: C# : What if a static method is called from multiple threads?).
But when your classes have static variables and you access them within a static method, there is a trade off: When doing multithreading, the access to the static variables must be synchronized. That's the reason why the singleton pattern doesn't work as good as some believe: Instantiation costs, even more if it's only singlethreaded.
Rules of thumb? Static methods with no static class variables are always good. But static classes with variables can become very evil when doing multithreading. Therefore beware of static bottlenecks!
I've created a class which was static first, this class does not persist state (does not keep context or any variables) is just a list of functions.
But the class is not very used in the app so I decided to make class instantiable.
Why?
Because I think an instantiable class would use less memory as it is not available during the whole app life cycle.
Is this right?
A static class uses more memory than a non-static class?
Thank you
I think you've misunderstood how classes work. Any kind of class is "available" throughout the lifetime of the app. Memory used for the class itself (the methods etc) is very different to memory used by instances. Unless you actually create an instance of the class, it's irrelevant. And even static classes can be instantiated - it's just that they don't maintain an implicit reference to an instance of the enclosing class.
If your class doesn't actually require an implicit reference (i.e. it doesn't use it) then make it a static nested class - or pull it out as a top-level class anyway. (Nested classes can be a pain sometimes - the rules around top-level classes are simpler.)
A static class as such doesn't use more memory than a non static one. All classes are always available in an application - you can always use a static class or create an instance of a non static one.
If you have only methods in your class (which are of a helper method types) a static class is more convenient to use (no need to create an instance) and won't affect your memory usage.
Is there any difference between a Singleton class and a class with
all static members (i.e. methods and attributes).
I could not find any instance where 'all static member class' would not achieve
the same functionality as class properly implementing Singleton pattern?
For eg. java.lang.Runtime is a proper Singleton class whereas java.lang.System has all static method for access and merely has a private constructor to avoid external construction . Does anybody know why classes like Runtime are made Singleton and not implemented like java.lang.System.
Is it merely because it would be a cleaner design (i.e. mimics an object more realistically) or is there some performance benefit here?
Yes, there's a difference - a singleton can implement an interface.
Also, what looks like a singleton from the outside can actually be implemented via different classes, where the singleton access method (e.g. Runtime.getRuntime()) can create the right instance at execution time. I'm not saying that's what's happened here, but it's an option.
Well you can serialize and unserialize an object (and thus a Singleton) using the Serializable interface (on Java), but not a static class.
A singleton is instantiated once.
A static class is never instantiated.
I believe there is no difference between what you call a singleton and a class with all static methods/members in principle. In fact, I think that creating a class with all static members is a way of implementing the singleton idiom. Well, maybe in Java there is some kind of serious difference, but I'm speaking from the C++ point of view.
I think you should ask what's different between final class with private constructor and static class.
Because singleton is a class and implementation depends on programmer who programs this class.
It's same as ask what's differences between an object and static class.
A class can be extended to create another singleton (e.g. for testing purposes), or non-singleton class. static methods cannot be overidden, they can only be hidden in a sub class.
A common use for singletons with lazy initialization (aka Meyers singletons) is to control the order of static objects initialization (which, in C++, is undefined across different translation units). In this respect, singletons just behave like global objects, but whose order of construction behaves well.
It becomes quite difficult to control the order of destruction though. If you must rely on the singletons being destructed in some particular order (eg. a singleton logging class which should outlast other singleton instances), see Alexandrescu's book to witness the difficulty.
The primary purpose for singletons cited by the GoF is to provide a polymorphic service, where the singleton is an abstract base class, and the concrete type is decided at runtime. And, of course, there must only be one of them in the program.