I know of 2 ways to implement the singleton pattern in java and im wondering which one is better and why.
the first way is:
declare the constructor of the class private
have everything inside the class static - basiclly have the class instance itself be the singleton
second way is:
declare the constructor of the class private
have a static member to hold the singleton (which may be an instance of the class)
have a static getInstance() method
I tend to think that even though the second approach is the most common, the first approach may produce better code readability, both approaches seem similiarly efficient in runtime complexity, so i dont really get the reasons behind why the second approach is way more common and considered better practice...
enlighten me!
The first approach is not a singleton. A singleton is a class of which precisely one instance, no more, no less, can exist. The first thing is sometimes called a "static class", a "utility class," or an "uninstantiable class."
There are a number of things that you can do with a "real" singleton that you can't do with a utility class. For example, you can have a singleton that implements an interface or extends another class; you can't do that with the all-static-methods thing. The all-static-methods class is generally evidence that no object oriented design analysis was done
As far as how many ways there are to implement the singleton pattern in Java, there are actually quite a number of interesting ways, using different language features to defer initialization until absolutely needed: class loading, enumerations, or just a synchronized block and an if.
Testability of other classes that use the singleton is hampered by static methods. With an instance you can substitute a mock object or other forms of test double.
Advantages to the object-based singleton
Will your "singleton" ever, under any possibly non-imaginable circumstances, become a non-singleton?
Perhaps you'll want per-thread, per-connection, or some other categorization?
Door #2 leaves you with a future, without having to rewrite code.
You may have a singleton, but do you have only one implementation of that singleton? A common pattern is to have a factory method look at the runtime environment and make a determination as to which implementation of the "service" being offered by the singleton is appropriate. The commons-logging LogFactory is example of this type of singleton.
If I get your question, right.
Why is this #2
public class MySingleton {
static private MySingleton instance=new MySingleton();
private MySingleton() {}
static public MySingleton getInstance() { return instance; }
}
better than #1
...Sorry I don't get the first point...
-> Actually reading from other comments I got it. I confirm, having static methods doesn't mean you have a singleton. So the comparison is not even fair ;-/
Whatever it is, the reason why #2 is better is because of multi-threading.When the singleton is initialized from a static initializer, the jvm makes sure only one thread instantiates the class.
Well there are few interesting ways to implement singleton pattern. Let me recollect few of those implementations which i have read about:
The second approach you have mentioned in your question. (Not thread safe)
When you developing multithreaded applications you may have to use a lock (simple thread safety)
public sealed class Singleton
{
static Singleton instance=null;
static readonly object padlock = new object();
Singleton()
{
}
public static Singleton Instance
{
get
{
lock (padlock)
{
if (instance==null)
{
instance = new Singleton();
}
return instance;
}
}
}
}
Double check locking
public sealed class Singleton
{
static Singleton instance=null;
static readonly object padlock = new object();
Singleton()
{
}
public static Singleton Instance
{
get
{
if (instance==null)
{
lock (padlock)
{
if (instance==null)
{
instance = new Singleton();
}
}
}
return instance;
}
}
}
Not lazy, but thread-safe without using locks
public sealed class Singleton
{
static readonly Singleton instance=new Singleton();
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static Singleton()
{
}
Singleton()
{
}
public static Singleton Instance
{
get
{
return instance;
}
}
}
Fully Lazy Initialization
public sealed class Singleton
{
Singleton()
{
}
public static Singleton Instance
{
get
{
return Nested.instance;
}
}
class Nested
{
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static Nested()
{
}
internal static readonly Singleton instance = new Singleton();
}
}
The third approach wont work in java.Becos Java memory model doesn't ensure that the constructor completes before the reference to the new object is assigned to instance.
Hope this helps you.
Perhaps consider implementing a singleton using an enum:
public enum Singleton {
INSTANCE;
public void doStuff() {
System.out.println("Whoopee");
}
}
and call it like Singleton.INSTANCE.doStuff()
This is recommended in the book Effective Java by Josh Bloch
Related
I'm trying to create a framework where Singleton objects can get the core of their implementation from. The use for this is so if I make multiple Singleton classes, I don't need to re-write their (while simple) implementations over and over.
I tried this:
public abstract class Singleton
{
protected static final Lock mutex = new ReentrantLock(true);
// Not even subclasses are allowed to mess with `instance`.
private static Singleton instance = null;
// Here is the problem, static methods cannot be abstract.
protected static abstract Singleton init();
public static Singleton get()
{
mutex.lock();
// The super class has no idea how to instantiate
// this singleton, so let subclasses handle that
// via the abstract init method
if (instance == null)
instance = init();
mutex.unlock();
return instance;
}
}
But it really cannot work because the whole concept of static members with inheritance doesn't go well together.
My other option is to do:
public enum Singleton
{
INSTANCE
}
But since enum cannot be extended, I cannot do:
public enum MySingleton extends Singleton
{
// Member variables and functions here
...
}
I could have every implementation just be an enum and the only code I have to repeat (I think?) is INSTANCE unless I'm missing something? The only downside I see there is the Singleton is created at the beginning of the runtime and not on-demand later on in the program.
I could also do an interface but then I get stuck here:
public interface Singleton
{
Singleton instance = null;
default void set(Singleton s)
{
assert instance == null;
assert s != null;
// cannot do this, as `instance` is FINAL
instance = s;
}
}
What's the best way to do define a Singleton contract without having to retype the entire implementation over again?
Thanks
I read a lot of articles about Singleton, in most of which authors said that this variation of Singleton in Java:
public class Singleton {
private static Singleton instance = new Singleton();
private Singleton() {}
public static Singleton getInstance() {
return instance;
}
}
is NOT LAZY (EAGER then).
But I can't understand why, Singleton() constuctor will be invoked only on Singleton class initialization. I know several reasons, which can trigger class initialization:
Using new with constructor (but in this case constructor is private).
Accessing or setting up static field (here private).
Using static method.
With reflection: Class.forName("Singleton").
So here our object will be created only on using static method getInstance() (it is still LAZY initialization I guess) and with reflection (but reflection can ruin a lot of Singleton variations, except enum maybe).
Maybe I can't see something obvious, explain me please, where was I wrong?
Basically it's a matter of degrees of laziness. It's lazy in that it won't construct the singleton until the class is initialized, but it's eager in that there could be situations where you want to use the class without initializing the singleton itself.
For example:
public final class Singleton {
private static final Singleton instance = new Singleton();
private Singleton() {}
public static Singleton getInstance() {
return instance;
}
public static void sayHello() {
System.out.println("Hello!");
}
}
Calling Singleton.sayHello() will instantiate the singleton even if we don't want it to... so it's not as lazy as it could be.
You can get round this using a nested type:
public final class Singleton {
private Singleton() {}
public static Singleton getInstance() {
return Holder.instance;
}
public static void sayHello() {
System.out.println("Hello!");
}
private static class Holder {
private static final Singleton instance = new Singleton();
}
}
Now Singleton.Holder will only be initialized by using the getInstance method. It's lazy and thread-safe with no locking.
In my experience, usually a singleton class's only static method is the getInstance method, in which case they're equivalent (assuming you don't use reflection to initialize the type somehow, for example).
It is not lazy because the singeton object is created once the class is loaded.
A lazy Singleton would create the object when it is first used.
In my point of view, the goal of being Lazy is to control when the instance of the Singleton is created.
In this example, there is no control because there is a class variable (static member that is initialized when the class is initialized and not when getInstance() method is called).
That way, there is no control of when the Singleton is created.
But, if you initialize the variable, inside getInstance, you are getting control of when you want the Singleton to be created.
As you said, there are many examples of Singletons. I always try to go for Enums if I need them.
You can find examples here: https://connected2know.com/programming/java-singleton-pattern/
The standard method of implementing singleton design pattern is this:
public class Singleton {
private static Singleton instance = new Singleton();
public static Singleton getInstance() {
return instance;
}
private Singleton() {}
}
I was wondering if you could also implement it like this:
public class Singleton {
private Singleton() {}
public final static Singleton INSTANCE = new Singleton();
}
and if yes which version is better?
Neither. In both cases, a trusted consumer can invoke the private constructor via reflection. An additional problem is that it these implementation don't play nicely with serialization unless you take extra steps to make it so (by default, if you take the naïve approach, every time a Singleton is deserialized, it will create a new instance).
The correct solution is to use an enum that defines a single value.
public enum Singleton {
INSTANCE;
// methods
}
From Effective Java:
While this approach is yet to be widely adopted, a single-element enum type is the best way to implement a singleton.
Why you not use enum for realisation Singleton?
public enum SingletonEnum {
Instance;
private static String testStr = "";
public static void setTestStr(String newTestStr) {
testStr = newTestStr;
}
public static String getTestStr() {
return testStr;
}
public static String sayHello(String name) {
return "Hello " + name;
}
}
In my opinion first one is better as it looks more aligned to Object oriented approach.
While there's nothing particularly wrong with either solution, this solution from Wikipedia should give you the best compatibility and give you a thread-safe singleton:
University of Maryland Computer Science researcher Bill Pugh has written about the code issues underlying the Singleton pattern when implemented in Java.[11] Pugh's efforts on the "Double-checked locking" idiom led to changes in the Java memory model in Java 5 and to what is generally regarded as the standard method to implement Singletons in Java. The technique known as the initialization on demand holder idiom, is as lazy as possible, and works in all known versions of Java. It takes advantage of language guarantees about class initialization, and will therefore work correctly in all Java-compliant compilers and virtual machines.
The nested class is referenced no earlier (and therefore loaded no earlier by the class loader) than the moment that getInstance() is called. Thus, this solution is thread-safe without requiring special language constructs (i.e. volatile or synchronized).
public class Singleton {
// Private constructor prevents instantiation from other classes
private Singleton() { }
/**
* SingletonHolder is loaded on the first execution of Singleton.getInstance()
* or the first access to SingletonHolder.INSTANCE, not before.
*/
private static class SingletonHolder {
public static final Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance() {
return SingletonHolder.INSTANCE;
}
}
This question might be blunder to some of the Java Experts. But I would like to know why we create the objects in a static method like main but not in static block.
I understand that its going to create the object unnecessarily if we instantiate in static block and of course if we don't use it further. Are there any other things that are to be noted with this approach ? Can we relate this with Singleton Pattern ?
For example:
public class MyClass {
static {
AnotherClass object = new AnotherClass();
// Do Some operations here with object.
}
}
The main reason is control over when it actually gets executed.
The stuff in a static block will get executed the first time that the class is loaded and it's easy to accidentally cause a class to be loaded (for instance by referencing a constant on the class).
Having a static method means that you have complete control over when the method is called (because you have to explicitly call it).
In regards to singletons, the java idiom for eagerly loaded singletons initializes the instance as a static field. This will basically run just the same as a static block.
public class Singleton {
private static final Singleton instance = new Singleton();
private Singleton() {}
public static Singleton getInstance() {
return instance;
}
}
If you have a Java Singleton that looks like this:
public class MySingleton {
private static MySingleton instance;
private int member;
public static MySingleton getInstance(){
if(instance==null){
instance = new MySingleton();
}
return instance;
}
private MySingleton(){
//empty private constructor
}
public int getMemberA(){
return member;
}
public int getMemberB(){
return instance.member;
}
}
...is there a difference between getMemberA and getMemberB? That is, is there a difference between accessing the member with instance.xxx and just xxx?
Note: I am aware of the pros and cons of using the Singleton pattern!
Yes, there's a difference.
Your singleton implementation isn't currently threadsafe, which means it's possible to call getMemberB() on an instance other than the one referred to by instance, at which point you'll get a different result.
If your implementation were thread-safe (so genuinely only one instance could ever be created) then they'd be equivalent, and the simpler form would be much preferred.
No functional difference, but I find getMemberA() easier on the eye.
Note that your singleton isn't thread-safe. Two threads calling getInstance() concurrently could result in the creation of two objects. If this happens, the singleton contract is broken, and all bets are off.
No difference in behavior, however, I'd rather use 'return member' or even 'return this.member' as this looks more intuitively.
Thread-safety is a completely different topic and this simple singleton does not meet any thread-safe singleton requirements.
Your implementation of Singleton pattern uses lazy load technique. But it is not thread safe. We can use the synchronized keyword to make getInstance() method thread safe, but it hurts performance. It's better that we make double-check on private singleton member.
public class MySingleton {
private volatile static MySingleton instance;
public static MySingleton getInstance(){
if (instance == null) {
synchronized (MySingleton.class) {
if (instance == null) {
instance = new MySingleton();
}
}
}
return instance;
}
private MySingleton(){
//empty private constructor
}
}