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.
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.
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.
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;
}
}
I need to create a singleton class without keeping a static method.
How can i do that?
Create an enum with one instance
enum Singleton {
INSTANCE;
private Field field = VALUE;
public Value method(Arg arg) { /* some code */ }
}
// You can use
Value v = Singleton.INSTANCE.method(arg);
EDIT: The Java Enum Tutorial shows you how to add fields and methods to an enum.
BTW: Often when you can use a Singleton, you don't really need one as utility class will do the same thing. The even shorter version is just
enum Utility {;
private static Field field = VALUE;
public static Value method(Arg arg) { /* some code */ }
}
// You can use
Value v = Utility.method(arg);
Where Singletons are useful is when they implement an interface. This is especially useful for testing when you using Dependency injection. (One of the weakness of using a Singleton or utility class substitution in unit tests)
e.g.
interface TimeService {
public long currentTimeMS();
}
// used when running the program in production.
enum VanillaTimeService implements TimeService {
INSTANCE;
public long currentTimeMS() { return System.currentTimeMS(); }
}
// used in testing.
class FixedTimeService implements TimeService {
private long currentTimeMS = 0;
public void currentTimeMS(long currentTimeMS) { this.currentTimeMS = currentTimeMS; }
public long currentTimeMS() { return currentTimeMS; }
}
As you can see, if your code uses TimeService everywhere, you can inject either the VanillaTimeService.INSTANCE or a new FixedTimeService() where you can control the time externally i.e. your time stamps will be the same every time you run the test.
In short, if you don't need your singleton to implement an interface, all you might need is a utility class.
public class Singleton {
public static final Singleton instance = new Singleton();
private Singleton() {}
public void foo() {}
}
then use
Singleton.instance.foo();
Another approach is the singleton holder idiom which offers initialization on demand:
public class Something {
private Something() {
}
private static class LazyHolder {
public static final Something INSTANCE = new Something();
}
public static Something getInstance() {
return LazyHolder.INSTANCE;
}
}
Note that standalone singletons like this should be avoided where possible because it promotes global state, leads to hard-to-unittest code and depends on a single classloader context to name a few possible drawbacks.
Follow the Joshua Bloch enum recipe in "Effective Java" 2nd edition. That's the best way to create a singleton.
I don't understand why this comes up so much. Isn't singleton a discredited design pattern? The GoF would vote it off the island today.
You can use one of IoC containers (e.g. Google Guice) and use your class as singleton(eager or lazy - it depends on your needs). It's easy and flexible as instantiating is controlled by IoC framework - you don't need any code changes if, for example, you will decide to make your class not singleton later.
Use an object factory, fetch your singleton object from this factory.
ObjectFactory factory;
....
MySingletonObject obj = factory.getInstance(MySingletonObject.class);
of course, there are many frameworks to help you to achieve this.
the spring framework is a popular choice.
From within constructor you need to chceck if there is already instance of the class somewhere. So you need to store reference to your singleton instance in static variable or class. Then in contructor of singleton I would always check if there is existing instance of singleton class. If yes I wouldnt do anything if not I would create it and set reference.