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
}
}
Related
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/
Very often I see singleton built in this way:
public static MyClass instance() {
if (singleton == null) {
singleton = new MyClass();
}
return singleton;
}
If not for the lazy initialization effect, does the approach have any advantage over simply declaring a static instance like this?
public final static MyClass singleton = new MyClass();
No, in fact the other approach, i.e.:
public final static MyClass singleton = new MyClass();
might be better as, if you you have 2 threads calling the instance method at the same time you could get a race condition.
This is how Java in Practice says to do singletons:
private final static MyClass _instance = new MyClass();
public static MyClass getInstance() {
return _instance;
}
private MyClass() {}
Update Since #jon-skeet mentioned it there is really good discussion of Singletons in the book Effective Java by Joshua Block. One thing he points out is that if you want your Singleton to be serializable you can't just implement Serializable. You need to override the readResolve method as well. Use the above approach makes this easy:
private Object readResolve() throws ObjectStreamException {
return _instance;
}
Update 2: Checkout this excellent discussion on Singletons linked to by #mardavi: http://en.wikipedia.org/wiki/Singleton_pattern#Initialization_On_Demand_Holder_Idiom
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;
}
}
I am not sure, if anyone has asked this question before (If so apologies).
code copied from wikipedia.
public class Singleton {
private static final Singleton instance = new Singleton();
private Singleton() {}
public static Singleton getInstance() {
return instance;
}
}
How it is thread safe? is it(only) because there is no mutating state in this class?
what happens if I modify it like this
public class Singleton {
private static final Singleton instance = new Singleton();
private FancyClass obj1;
private FancyClass obj2;
//feel free to imagine all the getters and setters for obj1 and obj2,
// like getObj1() and so forth
//tricky method
public void doSomething() {
obj1.destroyEnemy();
obj2.destroyFriend();
}
private Singleton() {
obj1 = null;
obj2 = null;
}
public static Singleton getInstance() {
return instance;
}
}
I have no interest in design-patterns discussion, this is the kind of code, I am supposed to maintain. is the above 'singleton' thread safe, assuming that FancyClass is java standard library class.
You're right that the first example is safe only because there is no mutable state.
In the second example, the singleton isn't doing anything to make it threadsafe, whether it's safe depends on if FancyClass is threadsafe. Putting synchronized on the doSomething method would make it threadsafe.
Introducing getters and setters for obj1 and obj2 would also have the potential to create problems, those would have to be synchronized on the same lock as the doSomething method, and you would need locking even if FancyClass is threadsafe, because if different threads are changing things then those changes need to be made visible across threads.
The first code guarantees that all threads that call getInstance() get a reference to the same instance of Singleton.
For your implementation (second example), the same is true for obj1 and obj2, because they're created while the class itself is created and class creation is thread safe (can't be created twice/"in parallel" within the same classloader).
The doSomething() method is not thread safe. Make it synchronized if you need an atomic operation.
The Singleton pattern is not designed to be Thread Safe at all, just to be unique and forbidding creation of additional instances. The only part that is thread safe in you code is the Singleton instantiation private static final Singleton instance = new Singleton(); as it's invoked one time a class loading time.
But effectively, if there's no members in your class modified by a method invked concurently by external systems, your Singleton will be/stay ThreadSafe
About your code -
Since you are making your constructor private it will never be called. So declaring it null there makes no sense. Anyway instance variables are automatically assigned default values.
First of all the 1st code
public class Singleton {
private static final Singleton instance = new Singleton();
private Singleton() {}
public static Singleton getInstance() {
return instance;
}
}
is called Early initialization unlike lazy initialization in which you create instance only when needed. To make it thread safe you need to do the following
public class Singleton {
private static Singleton singleInstance;
private Singleton() {}
public static Singleton getSingleInstance() {
if (singleInstance == null) {
synchronized (Singleton.class) {
if (singleInstance == null) {
singleInstance = new Singleton();
}
}
}
return singleInstance;
}
Example is of lazy initialization but the concept remains the same.
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