Is this singleton lazy initializated? - java

I have code like this:
class Singleton {
private static final Singleton INSTANCE = new Singleton();
private Singleton() {
System.out.println("Singleton constructed.");
}
public static Singleton getInstance() {
return INSTANCE;
}
}
When we don't have any other static method that getInstance, is this singleton lazy initializated? As far as I know class is initialized only in some cases, like:
An Instance of class is created using either new() keyword or using
reflection using class.forName(), which may throw
ClassNotFoundException in Java.
An static method of Class is invoked.
An static field of Class is assigned.
An static field of class is used which is not a constant variable.
If Class is a top level class and an assert statement lexically nested within class is executed.
(Surce: http://javarevisited.blogspot.com/2012/07/when-class-loading-initialization-java-example.html#ixzz4IjIe2Rf5)
So when the only static method is getInstance and constructor is private there is no possibility to initialize Singleton class in any other way than using getInstance method (apart from reflection). So the object is created only when we need it so it's a lazy initialization, right? Or maybe I missed something?

You mentioned static methods and private constructor. Add another static field, something like:
static int NUMBER = 13;
in your Singleton class. And in the main method of other class:
System.out.println(Singleton.NUMBER);
then, you will see that your Singleton is not lazy initialized.
BUT, when your field is static FINAL:
static final int NUMBER = 13;
the Singleton is lazy initialized.
What is more, when you add static and non-static initialization blocks in your Singleton class:
{
System.out.println("non-static");
}
static {
System.out.println("static");
}
the order is: non-static, private constructor and then static, because you are instatiating an object as a value of static field. So, it is very tricky :)
In summary, in some cases your Singleton may be considered as lazy initialized but it is not in general.

It's initialized immediately so no, it's not. Typically a lazy initialization means you initialize it when you try to actually retrieve it but the field isn't initialized yet.
Lazy initialization is not about the class initializing -- it's about the field that's contained in it. In your case as soon as the class is loaded, the field will be initialized immediately.
Your example adapted to use lazy initialization:
class Singleton {
private static Singleton INSTANCE;
private Singleton() {
System.out.println("Singleton constructed.");
}
public static Singleton getInstance() {
if(INSTANCE == null) {
INSTANCE = new Singleton();
}
return INSTANCE;
}
}
This will only construct the singleton when it is actually requested and not just when the Singleton class is loaded in memory. In your situation, if it is loaded in memory then its static fields would be initialized (including your singleton field).

EDIT: I was wrong. A class is NOT loaded just by referencing it, like below:
System.out.println(Singleton.class);
A class is loaded by the class loader as soon as an instance is created, a static member is referenced, or by loading it programmatically:
Class<?> clazz = Class.forName("Singleton"); // fully qualified classname
The above statement causes the class to be loaded, and all static members and blocks will be processed in order of appearance in the class. In your example class this will cause the INSTANCE variable to be initialized (and the message to be printed to System.out). This proves that your approach does not guarantee lazy loading.
A better way to implement a lazy loading singleton is with the Singleton holder pattern:
class Singleton {
private static class Holder {
private static final Singleton INSTANCE = new Singleton();
}
private Singleton() {
// hide constructor
}
public static Singleton getInstance() {
return Holder.INSTANCE;
}
}

No, it is not lazy initialized.
Lazy mean on first call or never. In your case it is not on first call.
You can pass lazy initialization problem to SingletonHolder class. It will be initialized on first getInstance call.
public class Singleton {
private Singleton() {}
private static class SingletonHolder {
private static final Singleton instance = new Singleton();
}
public static Singleton getInstance() {
return SingletonHolder.instance;
}
}

If you're using .NET 4 (or higher), John Skeet recommends you do the following:
You can use the System.Lazy type to make the laziness really simple. All you need to do is pass a delegate to the constructor which calls the Singleton constructor - which is done most easily with a lambda expression.
public sealed class Singleton
{
private static readonly Lazy<Singleton> lazy = new Lazy<Singleton> (() => new
Singleton());
public static Singleton Instance { get { return lazy.Value; } }
private Singleton()
{
}
}
It's simple and performs well. It also allows you to check whether or not the instance has been created yet with the IsValueCreated property, if you need that.
The code above implicitly uses LazyThreadSafetyMode.ExecutionAndPublication as the thread safety mode for the Lazy. Depending on your requirements, you may wish to experiment with other modes.

Related

Use factory to build singleton object

I'm trying to create some singleton object with a factory:
public class MyObjectFactory {
private MyObject myObject;
public MyObject getInstance(boolean newInstance) {
if (newInstance) {
// return new object
} else {
// return the old object
}
}
}
I want to use the getInstance(boolean newInstance) method to generate a new object or reuse the existing singleton object.
if newInstance is true: I will generate a new singleton object
if newInstance is false: if myObject is null, then generate a new one and return, or if myObject is not null, just return it.
And this getInstance(boolean newInstance) must be thread safe. Any idea how?
According to your comment, this is one way to implement what you want:
public class MyObjectFactory {
private volatile MyObject inst;
public synchronized MyObject getInstance(boolean newInstance) {
if(newInstance) {
inst = new MyObject(...);
}
return inst;
}
}
Making the field volatile means that the value is not cached in the CPU, so changes are immediately visible to all threads. Making the method synchronized ensures that only one thread can enter it at the same time.
This is not how Singletons work. The whole point of a Singleton is to have a single instance across the program of a certain class. Parameterizing your factory method to either get a new instance or a previous one does not fall into the definition of a Singleton.
Also, the best Singleton implementation is known as the Bill Pugh Singleton:
public class BillPughSingleton {
private BillPughSingleton() {}
public static BillPughSingleton getInstance() {
return SingletonHelper.INSTANCE;
}
private static class SingletonHelper {
private static final BillPughSingleton INSTANCE = new BillPughSingleton();
}
}
The William Pugh implementation ensures multi-thread safety and the best performances as the nested static class is loaded by the class loader only when the method getInstance() is invoked. In fact, a static nested class is simply a static member of the outer class (no difference from a static field or a static method in terms of creation time). The static member is created only when the class is used, so since no instances of the BillPughSingleton can be created with a constructor, a single thread-safe instance is generated only when the outer class is used via the getInstance() method.
EDIT
If what you're asking is something that either creates a new instance if this is null or returns/overrides the existing one. Then, what you need is not a singleton but a retriever class. Besides, you should also take into consideration in your design whether this retriever class will be used in multi-thread scenarios or not. Here is a basic implementation:
class MyRetriever {
private static MyClass instance;
//Private constructor to force the factory method invocation
private MyRetriever() {}
//Synchronizing the method in order to avoid race condition and establish a happens-before relationship between threads
public synchronized static MyClass getInstance(boolean flagOverride) {
if (flagOverride || instance == null){
instance = new MyClass();
}
return instance;
}
}

Why does accessor method of the object in Singleton Design Pattern have to be "static?

In singleton design pattern, we restrict creation of objects to a single object using private constructor.
To provide a global handle to it, we use a "public static" method.
My question is why static is needed here? Why not just public?
Short answer:
Assume you have a Singleton class:
public class Singleton {
...
}
Then the constructor is probably private which means you cannot use new Singleton() from another class.
So the only way to access something that is inside the Singleton class would be using Singleton.methodName() or Singleton.fieldName.
But in order to do this then these methods and fields cannot be part of an object, they have to be static. And the getSingleton() or getInstance() method is no exception.
Answer with examples:
Assume you have a Singleton class:
public class Singleton {
}
We can now add the constructor. But it can not be public, since if it is public then you can just use new Singleton() from every other class and then it would not be a Singleton anymore. So the class would now look like this.
public class Singleton {
private Singleton(){
}
}
Now that the constructor is private this means that you cannot instantiate the class from another class it can also be instantiated from inside the Singleton class. So we should add the getInstance() or getSingleton() method.
public class Singleton {
private Singleton(){
}
public Singleton getSingleton(){
return null;
}
}
But now we cannot access it since the getSingleton() method can only be used on an object and we cannot instantiate a Singleton object from outside the class. So the getSingleton() needs to be accessed by using Singleton.getSingleton() and therefore it has to become a static method.
public class Singleton {
private Singleton(){
}
public static Singleton getSingleton(){
return null;
}
}
The answer so far should answer the question but it is not a functional Singleton class. So please continue reading for the complete answer.
Now we also want to return the instance of the Singleton from the getSingleton() method. So we also want a field called instance of singleton to point to the instance of the Singleton class.
public class Singleton {
private Singleton instance;
private Singleton(){
}
public static Singleton getSingleton(){
return instance;
}
}
But now the instance field is not accessible by the get getSingleton() method since the way the class is written right now the instance is a field of an the object and not the class, so the instance field has to become static as well.
public class Singleton {
private static Singleton instance;
private Singleton(){
}
public static Singleton getSingleton(){
return instance;
}
}
And now the final problem is that the variable instance is not instantiated anywhere so it will always return null. So we have to check in the getSingleton() that if the instance is null then create a new Singleton() and make the instance field point to it.
public class Singleton {
private static Singleton instance;
private Singleton(){
}
public static Singleton getSingleton(){
if(instance == null){
instance = new Singleton();
}
return instance;
}
}
If you want a thread safe Singleton class you can use something like this instead (suggested by Boris the Spider):
public enum Singleton {
INSTANCE;
private Singleton(){
// TODO
}
}
And now the Singleton is complete.
If the method is public and no static you will need an instance of the class to be able to call that method.. that makes no sense.
static method instead can be invoked with no instance since they belong the class

Singleton Pattern time of object instantiation

This may seem like a silly question, but I was wandering when creating a class following the singleton pattern, at what point is the object instantiated?
e.g. private static SingleObject instance = new SingleObject();
with the method getInstance() defined by:
public static SingleObject getInstance(){
return instance;
}
So 'instance' is a static variable which refers to an instance of SingleObject. But at what point is it actually instantiated and loaded into memory? (If that makes any sense)
It's instantiated the time the class is loaded (that's the time static members are initialized), which is the first time any reference to this class is made. If getInstance is the only member exported by this class (i.e. the only method or member accessible from outside this class), the instance is created the first time getInstance() is called.
It depends. A typical implementation of the Singleton pattern looks like:
class SingleObject {
private static SingleObject instance;
private SingleObject(){
}
public SingleObject getInstance() {
if(instance == null) {
instance = new SingleObject();
}
return instance;
}
}
in which case it's instantiated on the first call to getInstance. But there's no universal rule as to when it needs to be done. A Singleton could also be implemented as:
class SingleObject {
private static SingleObject instance = new SingleObject();
private SingleObject(){
}
public SingleObject getInstance() {
return instance;
}
}
in which case it would be instantiated when the class loads. Wikipedia has a few examples of different implementations.

Why private static field = new Singleton is not lazy in Java?

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/

What are the advantages and disadvantages of creating an Object in static block in Java?

This question might be blunder to some of the Java Experts. But I would like to know why we create the objects in a static method like main but not in static block.
I understand that its going to create the object unnecessarily if we instantiate in static block and of course if we don't use it further. Are there any other things that are to be noted with this approach ? Can we relate this with Singleton Pattern ?
For example:
public class MyClass {
static {
AnotherClass object = new AnotherClass();
// Do Some operations here with object.
}
}
The main reason is control over when it actually gets executed.
The stuff in a static block will get executed the first time that the class is loaded and it's easy to accidentally cause a class to be loaded (for instance by referencing a constant on the class).
Having a static method means that you have complete control over when the method is called (because you have to explicitly call it).
In regards to singletons, the java idiom for eagerly loaded singletons initializes the instance as a static field. This will basically run just the same as a static block.
public class Singleton {
private static final Singleton instance = new Singleton();
private Singleton() {}
public static Singleton getInstance() {
return instance;
}
}

Categories

Resources