Singleton Pattern time of object instantiation - java

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.

Related

Is this a valid Singleton class in a single threaded environment?

The most common example of a Singleton class in a single threaded environment is below:
{
private static Singleton obj;
// private constructor to force use of
// getInstance() to create Singleton object
private Singleton() {}
public static Singleton getInstance()
{
if (obj==null)
obj = new Singleton();
return obj;
}
}
As per my understanding the following can also be considered a Singleton, isn't it?
public class SingleTon {
static SingleTon s;
SingleTon getInstance() {
if (s == null) {
s = new SingleTon();
}
return s;
}
public static void main(String[] args) {
SingleTon s1 = new SingleTon();
s1 = s1.getInstance();
SingleTon s2 =new SingleTon();
s2 = s2.getInstance();
}
}
The difference in the second case is, I am not adding a private constructor and even though 2 different instances got created initially, by reassigning the value of getInstance, we are making the instances use the same object.
Please let me know if my understanding is correct.
For Single threaded env your first class is singleton but not second one.
For a singleton class, there must exist only a single object inside JVM but in your second case you haven't made constructor as private so by default at compile time compiler will add default public constructor and this will break the rule of singleton because whenever you will call new Singleton(), it will return a new instance so there is no meaning of having getInstance method with public constructor.
For a singleton class private constructor is must so that it cant be initialised from outside the class.
Second one is not Singleton, constructor must be private for singleton class.
You can use early initialisation as well to create singleton class -
{
private static Singleton obj = new Singleton();
private Singleton() {}
public static Singleton getInstance()
{
return obj;
}
}

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

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 Class creating more than one object when called from outside the class

I wrote a program to call a singleton class from inside the class main. I also wrote an other class from which I am trying to create a object for the Singleton class. I found that I am able to create only one object when I tried from the other class but when I tried to call the method from the same class it creates more than one object. I couldnt understand what is different from same class main method and other class main method.
Here are the classes:
SingleTonClass.java
public class SingleTonClass {
private static SingleTonClass obj = null;
private SingleTonClass() {
System.out.println("Private Constructor is called");
}
public static SingleTonClass CreateObj() {
if (obj == null) {
obj = new SingleTonClass();
}
return obj;
}
public void display() {
System.out.println("The Ojecte creation complete");
}
public void display1() {
System.out.println("The second obj creation is comeplete");
}
public static void main(String[] args) {
SingleTonClass stc = new SingleTonClass();
SingleTonClass stc1 = new SingleTonClass();
SingleTonClass stc2 = new SingleTonClass();
// stc.display();
// stc1.display1();
}
}
SingleTonClassTest.java
public class SingleTonClassTest {
public static void main(String[] args) {
SingleTonClass stc=SingleTonClass.CreateObj();
SingleTonClass stc1=SingleTonClass.CreateObj();
SingleTonClass stc2=SingleTonClass.CreateObj();
}
}
Rather than doing:
private static SingleTonClass obj=null;
You should use: (sorry for changing your weird class name at the same time).
private static final Singleton INSTANCE = new Singleton();
To instantiate the only instance of your Singleton.
After that, you are not going to do some mystical retrieval like:
public static SingleTonClass CreateObj()
{
if (obj==null)
{
obj= new SingleTonClass();
}
return obj;
}
Instead, you should define getInstance() method for retrieving your Singleton.
public static Singleton getInstance() {
return INSTANCE;
}
After these modiciations, your Singleton class should look like the following:
public class Singleton {
private static final Singleton INSTANCE = new Singleton();
private Singleton() {
// This is called only once
System.out.println("Private Constructor is called");
}
public static Singleton getInstance() {
return INSTANCE;
}
public static void main(String[] args) {
// Even if you ask 100 times, this will only return the same INSTANCE
Singleton stc = Singleton.getInstance();
Singleton stc1 = Singleton.getInstance();
Singleton stc2 = Singleton.getInstance();
}
}
And running it will, output:
Private Constructor is called
to your cmd or terminal.
As a final note, as #Swapnil stated already: private Singleton() { ... } declaration is used to indicate that only the Singleton class itself is able to create the instance, which makes sense and rather than doing private static final Singleton INSTANCE = new Singleton(); you can further optimize your code by using an enum constant to store instance (noted by #JonK). For further reading I recommend: singleton pattern in java
Cheers.
The whole point of having a private constructor in implementing a singleton pattern is that you shouldn't be able to invoke it from outside the class, to avoid object creation directly. You're invoking it from inside the class. Hence, the problem.
Singleton is no magic, you need to have a method like getInstance() inside your singleton and this method should ensure there's only once instance.
Rather than creating new object of Singleton class every time get the instance of singleton class. There are various ways to define singleton class.
Here is one way to crate thread safe Singleton class. for more check out this link http://www.journaldev.com/1377/java-singleton-design-pattern-best-practices-examples#bill-pugh-singleton
public class BillPughSingleton {
private BillPughSingleton(){}
private static class SingletonHelper{
private static final BillPughSingleton INSTANCE = new BillPughSingleton();
}
public static BillPughSingleton getInstance(){
return SingletonHelper.INSTANCE;
}
}
Singleton Class: We can create only one object of this class.
Let's take an example:Since every thing in Java is object so I am giving you a real life example. You have a house and there is lock in it. This lock has only one key and if any one from outside wants to enter or access any thing in your house then he should have that unique key. Means this constraint applies only on outsiders. If anyone already present in the house then he can do anything and there is no restriction for him.
In the same way private constructor does not let any anyone to create second object of that class but you can make multiple objects within the same class because private methods only accessed by same class.
Singleton is Design pattern and here in your code design is like this, CreateObj() is static method of SingletonClass which checks if object is null then create the object by calling the constructor otherwise it is returning the same object.
You can not make objects of singleton class outside the class because the constructor is private.
Constructor instantiate the object. if the constructor itself is private then the object will never be instantiated outside the class rather you can use getInstance method. then you can access its features outside the class.

Categories

Resources