Static method and variable:
public class Singleton{
private static Singleton singleton = null;
private Singleton(){
}
public static synchronized Singleton getInstance(){
if(singletion == null)
singleton = new Singletion();
return singleton;
}
}
Second after Java 1.5
public class Singleton{
private static volatile Singleton singleton = null;
private Singleton(){
}
public static Singleton getInstance(){
if(singleton == null){
synchronized(this){
if(singleton == null){
singleton = new Singleton();
}
}
}
return singleton;
}
}
So what's the pros and cons for these two thread safe code and when should we use which?
The second is thread safe but the following is much simpler, and faster as it doesn't require a synchronized block.
public enum Singleton {
INSTANCE;
// define fields and methods here.
}
to access
Singleton.INSTANCE.method();
Note: an enum can implement an interface if you need.
Both implementations are thread-safe and valid.
The former is shorter. It is more readable and maintainable.
The latter is faster, and it's also faster than most people think. Depending on the implementation of the Java VM, reading a volatile variable is as fast as reading a non-volatile variable on x86. That means the overhead occurs only during the initialaztion. But as soon as the singleton has been initialized, there is no overhead at all.
If performance is really an issue, you should use the latter. Otherwise use the former, because the need for readability and maintainability is often underestimated.
The safest way to go about doing a thread-safe singleton is via the initialisation on demand holder idiom:
public class Foo {
private Foo() {}
private static class Holder {
private static final Foo INSTANCE = new Foo();
}
public static Foo getInstance() {
return Holder.INSTANCE;
}
}
This works in Java versions that didn't properly support the volatile keyword. The neat thing about this pattern is that it uses implicit locking only on the first access of getInstance. After that, access is unsynchronized. This is due to a fun little quirk of memory management and static loading in Java.
Both examples are of lazy initialization of singleton i.e. you initialize the singleton at the moment you need.The second example is an example of double checked locking which is primarily aimed at thread-safe.
The second one 'double checked' singleton is faster because it don't need to acquire lock whenever you ask for instance (despite first calls). Anyway best way to control life cycles of your objects is using dependency injection.
The first one is not thread safe. It would be thread safe if getInstance was synchronized.
If you need thread safety, use the second one.
There is a much simpler third way though, which is slightly different (the Singleton gets created at a different time):
public class Singleton{
private static final Singleton singleton = new Singleton();
private Singleton(){
}
public static Singleton getInstance(){
return singleton;
}
}
Related
I am trying to create a global connection pool for my Java app.
My problem is that when I use the following approach:
package mypackage;
public class Singleton
{
private static MyPool connPool;
private Singleton() {}
public MyPool getPool() {
if (connPool == null)
connPool = new MyPool();
return connPool;
}
}
Now if I have two classes A and B which import Singleton class above using
import mypackage.Singleton;
Then I will end up invoking new MyPool() twice, which means I will open double the connections to my resource (such as database). How can I ensure that I only create the pool one time in my application?
I found some complicated ways of accomplishing this on the internet using reflection. Is there an easier (and/or better) way?
I think you are looking for a thread-safe implementation of a Singleton class here. Of course, the way to achieve this is using enums, but for your case, you can implement double-check locking to ensure no two threads can call new MyPool() simultaneously.
Also, I think in your code, you are actually implementing a factory class, not really a singleton. Your MyPool is a different class than Singleton, which could have a public constructor.
I have made the appropriate changes with comments.
Double check-locking basically just checks the thread-safety before and after null-check, because the whole method is not synchronized, so two threads can indeed get the null value in the condition even after synchronization block, hence the second synchronization.
Also, I think your getPool() should be static. You won't be able to call getPool() without an explicit object of Singleton, which I think you don't need.
Corrected version:
package mypackage;
public class Singleton{
// Instance should be of type Singleton, not MyPool
private static Singleton connPool;
private Singleton() {}
// *static* factory method
public static Singleton getPool() {
// Double-check-locking start
synchronized(Singleton.class){
if (connPool == null){
// Double-check-locking end
synchronized(Singleton.class){
//create Singleton instance, not MyPool
connPool = new Singleton();
}
}
}
return connPool;
}
}
We had design patterns in school and learned the implementation of a singleton (lazy / not thread safe one) like this:
package com.crunchify.tutorials;
public class CrunchifySingleton {
private static CrunchifySingleton instance = null;
protected CrunchifySingleton() {
}
// Lazy Initialization (If required then only)
public static CrunchifySingleton getInstance() {
if (instance == null) {
// Thread Safe. Might be costly operation in some case
synchronized (CrunchifySingleton.class) {
if (instance == null) {
instance = new CrunchifySingleton();
}
}
}
return instance;
}
}
Now I found the implementation like this:
package com.crunchify.tutorials;
public class ThreadSafeSingleton {
private static final Object instance = new Object();
private ThreadSafeSingleton() {
}
// Runtime initialization
// By defualt ThreadSafe
public static Object getInstance() {
return instance;
}
}
Now I am wondering when the first implementation makes more sense to use, because according to http://crunchify.com/thread-safe-and-a-fast-singleton-implementation-in-java/ the second one is thread safe and needs less lines.
Difference is in the time singleton object is instantiated. Second snippet instantiates singleton object only once at class instantiation time. It is useful if no additional data required for this process. Note that if instantiation error occured (does not matter in that simple case: just Object) singleton class would not be available at all.
First snippet instantiates singleton object when it is being requested. You may modify that class to provide some mechanism to store any initialization data and/or catch instantiation errors.
how to prevent multiple instances of a Singleton due to whatever reasons. Double checked locking of Singleton is a way to ensure only one instance of Singleton class is created through application life cycle. As name suggests, in double checked locking, code checks for an existing instance of Singleton class twice with and without locking to double ensure that no more than one instance of singleton gets created.
This question already has answers here:
What is an efficient way to implement a singleton pattern in Java? [closed]
(29 answers)
Closed 6 years ago.
I'm trying to learn about the Singleton design pattern and I found two different ways of only creating 1 instance.
public class Singleton {
private static Singleton instance; // attributes omitted
private Singleton() {
// omissions
}
public static Singleton instance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
// other methods omitted
}
public class Singleton {
private static int bound = 1;
public Singleton() {
if (bound == 0) {
throw new RuntimeException(
"Singleton: No more objects must be created");
}
bound--;
}
}
Which is preferred to use and why? Are they equally as good?
Not sure about the Java way to do it but in my opinion I would just use the first way. I consider that it would be bad to throw and exception in your constructor and to expose publicly
Since you only want to get your unique instance the constructor should be private.
The first of your methods is a common way to try to implement a lazily-created singleton. It has some issues such as lack of thread safety, although they can be overcome via mechanisms like synchronization.
The second of your methods is truly vile. Exceptions should only be used to indicate exceptional conditions in the code. If you don't want somebody to create an instance of the class, don't let them - you can take control of the instantiation. Forcing them to catch an exception is a totally unnecessary burden on users of your class. (And it's not thread safe either).
A single-element enum is the best and easiest way to create a singleton.
However, there are certain circumstances in which you can't use an enum, for instance if your class needs to extend another class:
If you can initialize the instance eagerly, just do that:
class Singleton /* extends Blah */ {
private static final Singleton INSTANCE = new Singleton();
static Singleton getInstance() { return INSTANCE; }
}
If you want to defer initialization until it is required, you can use the lazy holder idiom:
class Singleton /* extends Blah */ {
private static class Holder {
private static final Singleton INSTANCE = new Singleton();
}
static Singleton getInstance() {
return Holder.INSTANCE;
}
}
The Holder class is not initialized until getInstance() is called, so the Singleton instance is not created until then.
It should be noted that singletons are considered by some to be a design antipattern.
Don't use either. As of Java 5, the preferred technique is to use an enum with a single value, usually named INSTANCE.
In the below snippet, Singleton1#INSTANCE is not final, while Singleton2#INSTANCE is:
public class Singleton1 {
private static Singleton1 INSTANCE = new Singleton1();
private Singleton1() {}
public static Singleton1 getInstance() {
return INSTANCE;
}
}
public class Singleton2 {
private static final Singleton2 INSTANCE = new Singleton2();
private Singleton2() {
public static Singleton2 getInstance() {
return INSTANCE;
}
}
What is the benefit of Singleton2 over Singleton1 (if any)?
There is none, Java wise. Class initialization happens atomically, within locks. No thread will be able to see Singleton1#INSTANCE partially created.
At this point, use final to clarify (to developers) that this field should not change.
I'm fairly certain that the answer is none for performance. It could prevent a bug if someone were to try and modify the reference at some point during the maintenance cycle.
final is basically used for two purposes in java -
1) For immutability - If a field is final, then it can only be initialized only once. So, if INSTANCE is not final then you can reinitialize creating one more object but this can only be done as constructor is private. So, basically final can avoid any other bugs which can be introduced at later stage as mentioned by Elliott.
2) To ensure that object is properly constructed before publishing (it is in context of multithreading) but since we are instantiating the INSTANCE on class loading (eager loading). It will not cause any issues. It will be created long before it will be used.
Is this singleton design pattern correct ? I mean what's the need of checking the object is null or not when it's static and the method is synchronized .
public class MySingleton {
int val = 10;
private static final MySingleton singleton = new MySingleton();
private MySingleton() { }
public static synchronized MySingleton getSingleton() {
return singleton;
}
}
You don't need to make your method synchronized. The fact that the variable is initialized in a static initializer is enough. Also, your val variable should almost certainly be private...
The double-checked locking pattern (with the nullity checking) is usually used when you don't want a synchronized method and you don't want a static initializer. (To my mind it's unnecessarily complex and brittle in almost all cases.)
Another option would be to use an enum:
public enum MySingleton {
INSTANCE;
private int val = 10;
// Presumably something to use val
}
Using an enum enforces the singleton-ness and even gets it right in the face of serialization. It's also a pretty simple way of doing it with no actual code :) On the other hand, it's never felt entirely right to me...
You can do it like that, but in many cases you can use "lazy evaluation" - you create the instance the first time it is requested:
public class MySingleton {
private static MySingleton singleton = null
private MySingleton() { }
public static synchronized MySingleton getSingleton() {
if (singleton == null) {
singleton = new MySingleton();
}
return singleton;
}
}
The best pattern is the one given by Joshua Bloch in his book Effective Java, using an Enum :
public enum MySingleton {
INSTANCE;
public void doSomething() {
}
}
Quoting the book :
"This approach is functionally equivalent to the public field approach, except that it is more concise, provides the serialization machinery for free, and provides an ironclad guarantee against multiple instantiation, even in the face of sophisticated serialization or reflection attacks. While this approach has yet to be widely adopted, a single-element enum type is the best way to implement a singleton."