Why private static field = new Singleton is not lazy in Java? - 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/

Related

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

Is this singleton lazy initializated?

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.

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.

2 implementations of Singleton

I know of 2 ways to implement the singleton pattern in java and im wondering which one is better and why.
the first way is:
declare the constructor of the class private
have everything inside the class static - basiclly have the class instance itself be the singleton
second way is:
declare the constructor of the class private
have a static member to hold the singleton (which may be an instance of the class)
have a static getInstance() method
I tend to think that even though the second approach is the most common, the first approach may produce better code readability, both approaches seem similiarly efficient in runtime complexity, so i dont really get the reasons behind why the second approach is way more common and considered better practice...
enlighten me!
The first approach is not a singleton. A singleton is a class of which precisely one instance, no more, no less, can exist. The first thing is sometimes called a "static class", a "utility class," or an "uninstantiable class."
There are a number of things that you can do with a "real" singleton that you can't do with a utility class. For example, you can have a singleton that implements an interface or extends another class; you can't do that with the all-static-methods thing. The all-static-methods class is generally evidence that no object oriented design analysis was done
As far as how many ways there are to implement the singleton pattern in Java, there are actually quite a number of interesting ways, using different language features to defer initialization until absolutely needed: class loading, enumerations, or just a synchronized block and an if.
Testability of other classes that use the singleton is hampered by static methods. With an instance you can substitute a mock object or other forms of test double.
Advantages to the object-based singleton
Will your "singleton" ever, under any possibly non-imaginable circumstances, become a non-singleton?
Perhaps you'll want per-thread, per-connection, or some other categorization?
Door #2 leaves you with a future, without having to rewrite code.
You may have a singleton, but do you have only one implementation of that singleton? A common pattern is to have a factory method look at the runtime environment and make a determination as to which implementation of the "service" being offered by the singleton is appropriate. The commons-logging LogFactory is example of this type of singleton.
If I get your question, right.
Why is this #2
public class MySingleton {
static private MySingleton instance=new MySingleton();
private MySingleton() {}
static public MySingleton getInstance() { return instance; }
}
better than #1
...Sorry I don't get the first point...
-> Actually reading from other comments I got it. I confirm, having static methods doesn't mean you have a singleton. So the comparison is not even fair ;-/
Whatever it is, the reason why #2 is better is because of multi-threading.When the singleton is initialized from a static initializer, the jvm makes sure only one thread instantiates the class.
Well there are few interesting ways to implement singleton pattern. Let me recollect few of those implementations which i have read about:
The second approach you have mentioned in your question. (Not thread safe)
When you developing multithreaded applications you may have to use a lock (simple thread safety)
public sealed class Singleton
{
static Singleton instance=null;
static readonly object padlock = new object();
Singleton()
{
}
public static Singleton Instance
{
get
{
lock (padlock)
{
if (instance==null)
{
instance = new Singleton();
}
return instance;
}
}
}
}
Double check locking
public sealed class Singleton
{
static Singleton instance=null;
static readonly object padlock = new object();
Singleton()
{
}
public static Singleton Instance
{
get
{
if (instance==null)
{
lock (padlock)
{
if (instance==null)
{
instance = new Singleton();
}
}
}
return instance;
}
}
}
Not lazy, but thread-safe without using locks
public sealed class Singleton
{
static readonly Singleton instance=new Singleton();
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static Singleton()
{
}
Singleton()
{
}
public static Singleton Instance
{
get
{
return instance;
}
}
}
Fully Lazy Initialization
public sealed class Singleton
{
Singleton()
{
}
public static Singleton Instance
{
get
{
return Nested.instance;
}
}
class Nested
{
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static Nested()
{
}
internal static readonly Singleton instance = new Singleton();
}
}
The third approach wont work in java.Becos Java memory model doesn't ensure that the constructor completes before the reference to the new object is assigned to instance.
Hope this helps you.
Perhaps consider implementing a singleton using an enum:
public enum Singleton {
INSTANCE;
public void doStuff() {
System.out.println("Whoopee");
}
}
and call it like Singleton.INSTANCE.doStuff()
This is recommended in the book Effective Java by Josh Bloch

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