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."
Related
Say Code for Singleton pattern:
class Singleton
{
private volatile static Singleton obj;
private Singleton() {}
public static Singleton getInstance()
{
if (obj == null)
{
synchronized (Singleton.class)
{
if (obj==null)
obj = new Singleton();
}
}
return obj;
}
}
obj in the above code is marked as Volatile, which means that whenever obj is used in the code, its always fetched from the main memory instead of using the cached value. So whenever if(obj==null) needs to be performed it fetches obj from main memory, though its value is set in the previous run. This is a performance overhead of using volatile keyword. How do we avoid it?
You have a serious miss-understanding what volatile does, but to be fair the internet and stackoverflow including is just polluted with wrong or incomplete answers about this. I also admit that I think I have a good grab about it, but sometimes have to re-read some things again.
What you have there shown - is called the "double check locking" idiom and it's a perfectly valid use-case to create a singleton. The question is if you really need it in your case (the other answer has shown a far more simple way, or you can read the "enum singleton pattern" too if you want). It's a bit funny how many people know that volatile is needed for this idiom, but can't really tell why it is needed.
DCL is doing two things mainly - ensures atomicity (multiple threads can't not enter the synchronized block at the same time) and ensures that once created, all threads will see that created instance, called visibility. At the same time, it ensures that the synchronized block will be entered a single time, all threads after that will not need to do that.
You could have easily done it via:
private Singleton instance;
public Singleton get() {
synchronized (this) {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
But now every single Thread that needs that instance has to compete for the lock and has to enter that synchronized block.
Some people think that: "hey, I can work around that!" and write (thus enter the synchronized block only once):
private Singleton instance; // no volatile
public Singleton get() {
if (instance == null) {
synchronized (this) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
As simple as that is - that is broken. And this isn't easy to explain.
it is broken because there are two independent reads of instance; JMM allow for these to be re-ordered; thus it is entirely valid that if (instance == null) does not see a null; while return instance; sees and returns a null. Yes, this is counter-intuitive, but entirely valid and provable (I can write a jcstress test to prove this in 15 minutes).
the second point is a bit more tricky. Suppose your singleton has a field that you need to set.
Look at this example:
static class Singleton {
private Object some;
public Object getSome() {
return some;
}
public void setSome(Object some) {
this.some = some;
}
}
And you write code like this to provide that singleton:
private Singleton instance;
public Singleton get() {
if (instance == null) {
synchronized (this) {
if (instance == null) {
instance = new Singleton();
instance.setSome(new Object());
}
}
}
return instance;
}
Since the write to the volatile (instance = new Singleton();) happens before setting the field that you need instance.setSome(new Object());; some Thread that reads this instance might see that instance is not null, but when doing instance.getSome() will see a null. The correct way to do this would be (plus making the instance volatile):
public Singleton get() {
if (instance == null) {
synchronized (this) {
if (instance == null) {
Singleton copy = new Singleton();
copy.setSome(new Object());
instance = copy;
}
}
}
return instance;
}
Thus volatile here is needed for safe publication; so that the published reference is "safely" seen by all threads - all it's fields are initialized. There are some other ways to safely publish a reference, like final set in the constructor, etc.
Fact of life: reads are cheaper than writes; you should not care what volatile reads do under the hood as long as your code is correct; so don't worry about "reads from main memory" (or even better don't use this phrase without even partially understanding it).
If you want to avoid using volatile, Then you can initialize when class loading and use private constructor to avoid creating new instance.
public class Singleton{
//Initialized when class loading
private static final Singleton INSTANCE = new Singleton();
//To avoid creating new instance of Singleton
private Singleton(){}
public static Singleton getSingleton(){
return INSTANCE;
}
}
You can use Lazy initialization with Holder static class
class Singleton
{
private Singleton() {}
private static class LazyLoader{
static final Singleton obj = new Singleton();
}
public static Singleton getInstance()
{
return LazyLoader.obj;
}
}
The important thing to note here is that the constructor should be fail-safe otherwise class loader will throw NoClassDefFoundError
You should use Enums for Singleton implementation.
Joshua Bloch suggests the use of Enum to implement Singleton design pattern because Java will ensures that any enum value is instantiated only once in a Java
program. The drawback is that the enum type is somewhat inflexible; for
example, it does not allow lazy initialization.
public enum EnumSingleton {
INSTANCE;
int value;
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
}
public class EnumDemo {
public static void main(String[] args) {
EnumSingleton singleton = EnumSingleton.INSTANCE;
System.out.println(singleton.getValue());
singleton.setValue(2);
System.out.println(singleton.getValue());
}
}
This post by has nicely listed other benefits of using Enums:
java singleton instantiation
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.
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;
}
}
Below is my Interface -
public interface IDBClient {
public String read(String input);
public String write(String input);
}
This is my Implementation of the Interface -
public class DatabaseClient implements IDBClient {
#Override
public String read(String input) {
}
#Override
public String write(String input) {
}
}
Now I am thinking to write Thread Safe Singleton Factory to get the instance of DatabaseClient so that I can call read and write method accordingly.. So I wrote like this by following the Initialization On Demand Holder idiom, it is still incomplete -
public class DatabaseClientFactory {
public static DatabaseClientFactory getInstance() {
return ClientHolder.s_instance;
}
private static class ClientHolder {
}
}
And I am not sure how to get the instance of DatabaseClient correctly in my above Factory? Do I need to add another method getClient() to get the instance of DatabaseClient and then call like this -
IDBClient client = DatabaseClientFactory.getInstance().getClient();
client.read(input); // or client.write(input)
You shold use Initialization-on-demand holder idiom, implementing your factory:
public class DatabaseClientFactory {
private DatabaseClientFactory() {}
private static class LazyHolder {
private static final DatabaseClient INSTANCE = new DatabaseClient();
}
public static DatabaseClient getInstance() {
return LazyHolder.INSTANCE;
}
}
This code doesn't need synchronization because of the contract of the class loader:
the class loader loads classes when they are first accessed
all static initialization is executed before anyone can use class
class loader has its own synchronization that make previous two points guaranteed to be thread safe
Here is very a nice description of correct implementation of singleton from Joshua Bloch's (one of the Java's creators) "Effective Java" book. I would strictly recommend to read at least this chapter.
A few comments:
If you want your DatabaseClient to be singleton, you have to move your factory method to this class and make it's constructor private. Otherwise there is no guarantee, that everyone will use your factory and someone won't create the second instance of this class;
Even with such approach there is no guarantee, that someone won't use reflection to create new instance of your "singleton";
If you decide for some reason to make your DatabaseClient serializable - you'll expose another ability of getting the second instance of "singleton" and will have to apply some additional techniques to avoid this (which are also not always effective).
If you still decide to go this way - you can use one of the approaches suggested by "AgilePro" or "user987339" (with moving that logic to the DatabaseClient). I believe method, described by "user987339" is preferable as it will help to make this initialization really lazy. It's not really the case with approach described by "AgilePro" cause each call to some of the static methods of that class will initialize all static fields.
If you want to get really robust singleton - I suggest you to use enums. So your DatabaseClient will look like:
public enum DatabaseClient {
INSTANCE;
DatabaseClient() {
}
public String read(String input) {
}
public String write(String input) {
}
}
And its usage:
final DatabaseClient databaseClient = DatabaseClient.INSTANCE;
P.S. One more note related to all approaches: if you get some exception during initialization of DatabaseClient - you'll get "java.lang.ExceptionInInitializerError" which won't let you to initialize this class any longer (for all further calls to this class you'll get "java.lang.NoClassDefFoundError").
This is all you need:
public class DatabaseClientFactory {
private static final DatabaseClient mySingleton = new DatabaseClient();
public static IDBClient getInstance() {
return mySingleton;
}
}
Note the private static final member that holds the singleton instance. Declaring it final prevents you fromwriting code that might create another instance. In this case we construct as static initialization time which happens before any thread can possibly access it, but you could construct with lazy initialization at run time if you desired. In this latter case you would need to make the method synchronized, which is a bit more overhead.
I made the factory method return the interface, but it could if you wish be declared to return the concrete class instead. If your concrete class has some additional methods beyond the interface you may want to do the latter.
Access it like this
IDBClient client = DatabaseClientFactory.getInstance();
It is thread safe because the variable that holds the singleton object is initialized at static initialization time, before any thread can access it. Since it is never changed after that, there is no possibility of a race condition.
This approach is simpler than that other answer because this involves only two classes, which is all you need: the factory class and the client class. One of the other answers requires three classes. This is a very small difference, since an extra class is a very small overhead, but if you believe that code should remain as simple as possible for maintenance reasons, then using three classes when two would do is a waste.
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.