The default way to implement singleton pattern is:
class MyClass {
private static MyClass instance;
public static MyClass getInstance() {
if (instance == null) {
instance = new MyClass();
}
return instance;
}
}
In an old project, I've tried to simplify the things writing:
class MyClass {
private static final MyClass instance = new MyClass();
public static MyClass getInstance() {
return instance;
}
}
But it sometimes fail. I just never knew why, and I did the default way.
Making a SSCCE to post here today, I've realized the code works.
So, I would like to know opinions..
Is this a aleatory fail code?
Is there any chance of the second approach return null?
Am I going crazy?
--
Although I don't know if is the right answer for every case, it's a really interesting answer by #Alfred:
I also would like to point out that singletons are testing nightmare and that according to the big guys you should use google's dependency injection framework.
The recommended (by Effective Java 2nd ed) way is to do the "enum singleton pattern":
enum MyClass {
INSTANCE;
// rest of singleton goes here
}
The key insight here is that enum values are single-instance, just like singleton. So, by making a one-value enum, you have just made yourself a singleton. The beauty of this approach is that it's completely thread-safe, and it's also safe against any kinds of loopholes that would allow people to create other instances.
The first solution is (I believe) not thread-safe.
The second solution is (I believe) thread-safe, but might not work if you have complicated initialization dependencies in which MyClass.getInstance() is called before the MyClass static initializations are completed. That's probably the problem you were seeing.
Both solutions allow someone to create another instance of your (notionally) singleton class.
A more robust solution is:
class MyClass {
private static MyClass instance;
private MyClass() { }
public synchronized static MyClass getInstance() {
if (instance == null) {
instance = new MyClass();
}
return instance;
}
}
In a modern JVM, the cost of acquiring a lock is miniscule, provided that there is no contention over the lock.
EDIT #Nate questions my statement about static initialization order possibly causing problems. Consider the following (pathological) example:
public ClassA {
public static ClassB myB = ClassB.getInstance();
public static ClassA me = new ClassA();
public static ClassA getInstance() {
return me;
}
}
public ClassB {
public static ClassA myA = ClassA.getInstance();
public static ClassB me = new ClassB();
public static ClassB getInstance() {
return me;
}
}
There are two possible initialization orders for these two classes. Both result in a static method being called before the method's classes static initialization has been performed. This will result in either ClassA.myB or ClassB.myA being initialized to null.
In practice, cyclic dependencies between statics are less obvious than this. But the fact remains that if there is a cyclic dependency: 1) the Java compiler won't be able to tell you about it, 2) the JVM will not tell you about it. Rather, the JVM will silently pick an initialization order without "understanding" the semantics of what you are trying to do ... possibly resulting in something unexpected / wrong.
EDIT 2 - This is described in the JLS 12.4.1 as follows:
As shown in an example in §8.3.2.3, the fact that initialization code is unrestricted allows examples to be constructed where the value of a class variable can be observed when it still has its initial default value, before its initializing expression is evaluated, but such examples are rare in practice. (Such examples can be also constructed for instance variable initialization; see the example at the end of §12.5). The full power of the language is available in these initializers; programmers must exercise some care. ...
The second example is preferable, since the first isn't thread safe (as pointed out in the comments). The first example uses a technique called lazy instantiation (or lazy initialization), which ensures that the Singleton instance isn't created unless it's actually needed. This isn't really necessary in Java because of the way Java handles class loading and static instance variable initialization.
I also would like to point out that singletons are testing nightmare and that according to the big guys you should use google's dependency injection framework.
Remember, you need to declare a private constructor to ensure the singleton property.
The second case could be even simpler with just
class MyClass {
public static final MyClass instance = new MyClass();
private MyClass() {
super()
}
}
`
As others have noted, the first is not thread-safe. Don't bother with it as the second is perfectly fine, and will instantiate the object only when MyClass is referenced. Further it makes the reference final which expresses the intent better.
Just make sure that the declaration
private static final MyClass INSTANCE = new MyClass();
is the first static declaration in your class to avoid risk of calls to getInstance() or INSTANCE before it is initialized.
Don't forget the SingletonHolder pattern. See this SO question.
I don't know the answers to your questions, but here is how I might structure the same thing.
class MyClass {
private static MyClass instance;
static {
instance = new MyClass();
}
private MyClass() { }
public static MyClass getInstance() {
return instance;
}
}
Related
I've been wondering about singletons in Java. By convention, a singleton is set up something like this:
private static MyClass instance = null;
public static MyClass getInstance(){
if (instance == null){
instance = new MyClass();
}
return instance;
}
private MyClass(){}
Recently I've switched to using the following:
public static final MyClass instance = new MyClass();
private MyClass(){}
This is a lot shorter, faster as there's no null-check, and typing MyClass.instance feels nicer to me than typing MyClass.getInstance(). Is there any reason why the second is not the mainstream way to do this?
The first version creates the instance the first time it is actually needed, while the second (the shorter) runs the constructor as soon as the class is initialized
A class or interface type T will be initialized immediately before the
first occurrence of any one of the following:
T is a class and an instance of T is created.
T is a class and a static method declared by T is invoked.
A static field declared by T is assigned.
A static field declared by T is used and the field is not a constant
variable (§4.12.4).
T is a top level class (§7.6), and an assert statement (§14.10)
lexically nested within T (§8.1.3) is executed. [...]
Invocation of certain reflective methods in class Class and in
package java.lang.reflect also causes class or interface initialization.
The initialization upon first usage is a performance improvement that may speed up the startup of the application if the code in the constructor makes expensive operations. On the other hand, the second version is straightforward to read and is automatically thread-safe.
Anyway, the state of the art is not creating singleton in either ways: for a bunch of KB you can get dependency injection libraries that make it working for you, and also handle more complex scenarios (for example look at Spring and AOP-backed injection).
Note: the first version is not thread safe in the pasted snippet
The way you have first described is known as lazy instantiation, i.e the object will only be created when it is first called. This method is not thread-safe as it is possible for a second thread to create a second instance.
If you read the following book:
Effective Java by Joshua Bloch
He explains that the best implementation of the singleton pattern is through the use of an Enum :
public enum Singleton {
INSTANCE;
public void doSomething() {
...
}
}
Then you would call your singleton through the Enum as follows:
public class Test {
public void test(){
Singleton.INSTANCE.doSomething();
}
}
This fits nicely with what you are saying in terms of it looks nicer and shorter to write but also guarantees there can never be a second instance.
I can think of two reasons:
The first is Encapsulation: you might have second thoughts about how and when your singleton is initialized, after your class has been exposed to client code. And an initialization method gives you more freedom as to changing your strategy later on. For example you might change your mind and decide to use two different constructors instead of one, according to another static variable's value at runtime. With your solution you're bound to using just one constructor at the time your class is loaded into memory, whereas with getInstance() you can change the initialization logic without affecting the interface to the client code.
The second is Lazy Initialization : with the conventional singleton implementation the MyClass object is loaded into memory only when needed by the client code for the first time. And if the client code doesn't need it at all, you save on the memory allocated by your application. Note that whether your singleton is needed or not might not be certain until the program runs. For example it might depend on the user interaction with the program.
However the Lazy Initialization is not something you might necessarily want. For example if you're programming an interactive system and the initialization of your singleton is time consuming, it might actually be better to initialize it when the program is loading rather than when the user is already interacting with it, cause the latter might cause a latency in your system response the first time getInstance() is called. But in this case you can just have your instance initialized with the public method as in:
private static MyClass instance = getInstance();
The best way to synchronize the threads is using Double Checked (to ensure that only one thread will enter the synchronized block at a time and to avoid obtaining the lock every time the code is executed).
public class DoubleCheckLocking {
public static class SearchBox {
private static volatile SearchBox searchBox;
// private attribute of this class
private String searchWord = "";
private String[] list = new String[]{"Stack", "Overflow"};
// private constructor
private SearchBox() {}
// static method to get instance
public static SearchBox getInstance() {
if (searchBox == null) { // first time lock
synchronized (SearchBox.class) {
if (searchBox == null) { // second time lock
searchBox = new SearchBox();
}
}
}
return searchBox;
}
}
Reflection: Reflection can be caused to destroy singleton
property of singleton class, as shown in following example:
// Java code to explain effect of Reflection
import java.lang.reflect.Constructor;
// Singleton class
class Singleton
{
// public instance initialized when loading the class
public static Singleton instance = new Singleton();
private Singleton()
{
// private constructor
}
}
public class GFG
{
public static void main(String[] args)
{
Singleton instance1 = Singleton.instance;
Singleton instance2 = null;
try
{
Constructor[] constructors =
Singleton.class.getDeclaredConstructors();
for (Constructor constructor : constructors)
{
// Below code will destroy the singleton pattern
constructor.setAccessible(true);
instance2 = (Singleton) constructor.newInstance();
break;
}
}
catch (Exception e)
{
e.printStackTrace();
}
System.out.println("instance1.hashCode():- "
+ instance1.hashCode()); //366712642
System.out.println("instance2.hashCode():- "
+ instance2.hashCode()); //1829164700
}
}
The pattern to create singletons seems to be something like:
public class Singleton {
private static final Singleton instance = new Singleton();
private Singleton(){
}
public static Singleton getInstance()
{
return instance;
}
}
However my problem is how do you Unit with a class like this if the Singleton Constructor does something that is not unit test friendly e.g. calls external service , jndi lookup etc.
I would think i could refactor it like:
public class Singleton {
private static Singleton instance;
private Singleton(){
}
public synchronized static Singleton getInstance()
{
if(instance == null)
instance = new Singleton();
return instance;
}
//for the unit tests
public static void setInstance(Singleton s)
{
instancce = s;
}
}
The problem now is that just for unit testability I have forced the getInstance to be synchronized so just for testing aspect it will have a negative impact on the real application. Is there a way around it, it seems any other sort of lazy initialization will not work because of the broken nature of double locking pattern in java.
You can use an enum as a Singleton
enum Singleton {
INSTANCE;
}
Say your singleton does something undesirable in unit tests, you can;
// in the unit test before using the Singleton, or any other global flag.
System.setProperty("unit.testing", "true");
Singleton.INSTANCE.doSomething();
enum Singleton {
INSTANCE;
{
if(Boolean.getBoolean("unit.testing")) {
// is unit testing.
} else {
// normal operation.
}
}
}
Note: there is no synchronised blocks or explicit lock needed. The INSTANCE will not be loaded until the .class is accessed and not initialised until a member is used. provided you only use Singleton.INSTANCE and not Singleton.class there won't be a problem with the value used to initialise changing later.
Edit: if you use just the Singleton.class this might not initialise the class. It doesn't in this example on Java 8 update 112.
public class ClassInitMain {
public static void main(String[] args) {
System.out.println("Printing a class reference");
Class clazz = Singleton.class;
System.out.println("clazz = " + clazz);
System.out.println("\nUsing an enum value");
Singleton instance = Singleton.INSTANCE;
}
static enum Singleton {
INSTANCE;
Singleton() {
System.out.println(getClass() + " initialised");
}
}
}
prints
Printing a class reference
clazz = class ClassInitMain$Singleton
Using an enum value
class ClassInitMain$Singleton initialised
You could use the Factory pattern to create the singleton, and switch implementations depending on evironment.
Or, avoid using the singleton pattern, and use Dependency Injection instead.
Double-checked locking is broken in every language, not just Java.
I tend to eschew singletons, but you can use the holder pattern just fine if you need them, as recommended in Josh Bloch's Effective Java:
public class Foo
{
static class Holder
{
static final Foo instance = new Foo();
}
public static Foo getInstance()
{
return Holder.instance;
}
private Foo()
{
}
// ...
}
EDIT: Repaired the reference.
You can dependency inject the singleton instance, override the getInstance() from the unit test code, use aspect oriented programming to intercept the method call and return a different object, or use a tool like jmockit which lets you mock pretty much anything, including statics, final classes, constructors, and all the stuff people normally say is "untestable."
One approach I've taken in legacy systems (where I wanted to make something testable with a minimal impact on the system's architecture) was to modify the factory methods (getInstance) to check a system property for an alternate implementation that I would instantiate instead. This was set to an alternate, mock object in the unit test suite.
As for the "double checked locking is broken" statement, that's not really true anymore, if you use the volatile keyword, and Java >= 1.5. It was broken (even with volatile) with 1.4 and earlier, but if you know your code will be run on only recent JVMs, I wouldn't worry about it. But I also wouldn't use a singleton anyway: having a DI/IOC container manage the lifecycle of the object would solve both of your problems (testability and synchronized accessor bottleneck) much more elegantly.
How about you lazy initialize in the build phase where you execute the unit tests. Then you change the code back to inline initialize before it's compiled for distribution.
Your production code is inline initialized, except during your tests. Perhaps this discrepancy btw production and testing code could introdude bugs, but which?
(Of course if this is a solution, we let a build phase + tool do the work. I see this facilitated with maven and dp4j).
This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Efficient way to implement singleton pattern in Java
I was reading this Best Singleton Implementation In Java, but its not thread safe.
As per wiki :
if(singleton==null) {
synchronized(Singleton.class) { //
this is needed if two threads are
waiting at the monitor at the // time
when singleton was getting
instantiated if(singleton==null)
singleton= new Singleton(); }
}
But Find Bugs utility gives two errors in this :
1. Double null check.
2. Incorrect lazy initialization of static field.
What is the best way,
Is it Correct :
synchronized (Singleton.class) {
if (singleton== null) {
singleton= new Singleton();
}
}
The most efficient/simplest way to make a lazy loading Singleton is just
enum Singleton {
INSTANCE
}
Note: there is no need for locking as class loading is thread safe. The class is final by default and the constructor cannot be called via reflection. The INSTANCE will not be created until the INSTANCE, or the class is used. If you are worried the class might be accidentally used you can wrap the singleton in an inner class.
final class Singleton {
private Singleton() { }
static class SingletonHolder {
static final Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance() {
return SingletonHolder.INSTANCE;
}
}
IMHO, you have to be pretty paranoid to consider this a better solution.
A lot has been written about this issue. Yes, the simple double-check-locking pattern is not safe. But you can make it safe by declaring the static instance as volatile. The new Java Memory Model specification adds some code-reordering restrictions for compilers when dealing with volatile, therefore the original risks are gone.
Anyway, I rarely really need this kind of lazyness when creating the instance, so I usually simply create it statically at class-loading time:
private static MyClass instance = new MyClass();
This is short and clear. As an alternative, if you really want to make it lazy, you can take advantage of the class loading characteristics and do this:
public class MyClass {
private static class MyClassInit {
public static final MyClass instance = new MyClass();
}
public static MyClass getInstance() {
return MyClassInit.instance;
}
...
}
The nested class will not be loaded until the first time you call getInstance().
The first code sample in the accepted answer for Efficient way to implement singleton pattern in Java is thread safe. The creation of the INSTANCE is performed by the class loader the first time the class is loaded; it's performed exactly once, and in a thread-safe way:
public final class Foo {
private static final Foo INSTANCE = new Foo();
private Foo() {
if (INSTANCE != null) {
throw new IllegalStateException("Already instantiated");
}
}
public static Foo getInstance() {
return INSTANCE;
}
}
(copied from What is an efficient way to implement a singleton pattern in Java?)
The 2nd code sample in the question is correct and thread-safe, but it causes synchronization on each call to getInstance(), which affects performance.
I understand that double locking in Java is broken, so what are the best ways to make Singletons Thread Safe in Java? The first thing that springs to my mind is:
class Singleton{
private static Singleton instance;
private Singleton(){}
public static synchronized Singleton getInstance(){
if(instance == null) instance = new Singleton();
return instance;
}
}
Does this work? if so, is it the best way (I guess that depends on circumstances, so stating when a particular technique is best, would be useful)
Josh Bloch recommends using a single-element enum type to implement singletons (see Effective Java 2nd Edition, Item 3: Enforce the singleton property with a private constructor or an enum type).
Some people think this is a hack, since it doesn't clearly convey intent, but it does work.
The following example is taken straight from the book.
public enum Elvis {
INSTANCE;
public void leaveTheBuilding() { ... }
}
Here is his closing arguments:
This approach [...] is more concise, provides the serialization machinery for free, and provides an ironclad guarantee against multiple instantiations, 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.
On enum constant singleton guarantee
JLS 8.9. Enums
An enum type has no instances other than those defined by its enum constants. It is a compile-time error to attempt to explicitly instantiate an enum type (§15.9.1).
The final clone method in Enum ensures that enum constants can never be cloned, and the special treatment by the serialization mechanism ensures that duplicate instances are never created as a result of deserialization. Reflective instantiation of enum types is prohibited. Together, these four things ensure that no instances of an enum type exist beyond those defined by the enum constants.
On lazy initialization
The following snippet:
public class LazyElvis {
enum Elvis {
THE_ONE;
Elvis() {
System.out.println("I'M STILL ALIVE!!!");
}
}
public static void main(String[] args) {
System.out.println("La-dee-daaa...");
System.out.println(Elvis.THE_ONE);
}
}
Produces the following output:
La-dee-daaa...
I'M STILL ALIVE!!!
THE_ONE
As you can see, THE_ONE constant is not instantiated through the constructor until the first time it's accessed.
I see no problem with your implementation (other than the fact that the lock for the singleton-monitor may be used by other methods, for other reasons, and thus, unnecessarily, prevent some other thread from getting the instance). This could be avoided by introducing an extra Object lock to lock on.
This Wikipedia article suggests another method:
public class Something {
private Something() {
}
private static class LazyHolder {
private static final Something INSTANCE = new Something();
}
public static Something getInstance() {
return LazyHolder.INSTANCE;
}
}
From the article:
This implementation is a well-performing and concurrent implementation valid in all versions of Java.
...
The implementation relies on the well-specified initialization phase of execution within the Java Virtual Machine (JVM); see section 12.4 of Java Language Specification (JLS) for details.
My preference is to just do:
class Singleton {
private static final INSTANCE = new Singleton();
private Singleton(){}
public Singleton instance(){
return INSTANCE;
}
}
It is rare that you need lazy initialization. You should always start with eager initialization and only change to lazy initialization if you see problems. Unless you have measured and pinpointed Singleton instantiation as the culprit of performance problem, just use eager initialization. It's simpler and more performant.
You could use enum for sure, but personally I don't bother because the benefit over normal eager instantiation is security (against reflection attack), and most of the time my code is vulnerable to such attacks anyways :p
Josh Bloch recommends 2 solutions:
1) worser:
class Singleton {
public static Singleton instance = new Singleton();
...
}
2) better:
public enum Singleton {
INSTANCE;
...
}
You can use this snippet of code from wiki
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 {
private static final Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance() {
return SingletonHolder.INSTANCE;
}
}
I see this idiom of initializing instance variables quite a bit
public class Test{
private Long l = 1l;
private MyClass mc = new MyClass();
public Test(){}
...
}
But I would prefer
public class Test{
private Long l;
private MyClass mc;
public Test(){
l = 1l;
mc = new MyClass();
}
...
}
Considering that these are non-final variables, are the 2 approaches equivalent or is one "more" correct than the other in terms of thread safety?
Thread safety isn't an issue because this happens at construction phase, and two threads cannot be constructing the same object. Well, if you let this escape from the constructor, it might be possible for another thread to access the object during construction, but you really shouldn't do that. Functionality-wise, the two options are the same, so even if there were thread-safety issues, they would affect both the same way.
The first option, of initializing the fields at their declaration, is not always possible if you need to do some computation that cannot be done in an initializer (even then, you can keep the initialization out of the constructor if you do it in an initializer block, though). But if either way is possible, then it's purely a style issue, and I don't think there is a clear preference among Java programmers, so go with whichever seems better to you.
since your variables are instance variables, not class variables, you don't have a thread safety issue during initialization using either method. I'm sure others will chime in if there's a Java-standard-recommended best practice.
I think it's the matter of personal preference and your project coding standards.
Just make sure you only initialize variables in one place ( either constructor, or inline ).
Having initialization work done in the constructor gives you a better place for exception handling.
They are both not thread-safe. If thread A constructs the object, then thread B may or may not observer an incompletely initialized Test object or MyClass object. The visibility guarantees after a constructor exits only apply to final fields.
See http://pveentjer.wordpress.com/2007/03/18/immutability-doesnt-guarantee-thread-safety/
In terms of thread safety, they are equivalent. Both will need to execute the same instructions, and if you prefer the second (which I agree with you in your preference) then I would use that. If you want thread safety around a constructor, you would need a synchronized call around the constructor call.
I am not sure if this was answered earlier. But, I have a doubt on the following scenario:
I am trying to create a #Component class where in, I have an instance variable. Now, I want to create a new object of the instance variable for each request. I am not sure which one is the right way to do it?
**Option 1:**
#Component
public class ClassA {
private ClassB classB = new ClassB();
public ClassB create(){
return classB;
}
}
**Option 2:**
#Component
public class ClassA {
private ClassB classB = null;
public ClassB create(){
classB = new ClassB();
return classB;
}
}
**Option 3:**
#Component
public class ClassA {
public ClassB create(){
ClassB classB = new ClassB();
return classB;
}
}