Use factory to build singleton object - java

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;
}
}

Related

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.

Java Singleton Design Pattern implementation [duplicate]

This question already has answers here:
How to write a Singleton in proper manner?
(13 answers)
Closed 8 years ago.
Can the implementation for a Singleton class can be as simple as below :
public class MyClass {
private final static MyClass myClass = new MyClass();
private MyClass() {}
public static MyClass getInstance() {
return myClass;
}
}
Over :
public class MyClass {
private final static MyClass myClass;
private MyClass() {}
public static MyClass getInstance() {
if(null == myClass) {
myClass = new MyClass();
}
return myClass;
}
}
Which is the better of the above implementations & why?
One thing that I observed is for the first implementation above the object constructor gets called before the static block if any.
Also if there is a thread-safe version of the 2nd implementation (may be a double null check and synchronized block), which should be preferred ?
Yes. And you can use that first version, but I would suggest you use an enum. Wikipedia's entry on Singleton says
In the second edition of his book Effective Java, Joshua Bloch claims that a single-element enum type is the best way to implement a singleton for any Java that supports enums.
Something like
public enum Singleton {
INSTANCE;
}
I would like to put some light on singleton design pattern.
Your First Code Snippet
public class MyClass {
private final static MyClass myClass = new MyClass();
public static MyClass getInstance() {
return myClass;
}
}
The above approach works fine but has drawback as instance is getting created much before actually it is required so at run-time think of the situation that if the instance is not big you can keep it if it is unused but if it big then what is the purpose of creating the instance.This approach is called Eager initialization
The code shown below indicates the second approach called Lazy initialization
public class MyClass {
private final static MyClass myClass;
public static MyClass getInstance() {
if(null == myClass) {
myClass = new MyClass();
}
return myClass;
}
}
But here again there is one drawback in your code,let's understand the defect in the above code
Let's consider we have tow threads namely T1 and T2 and both threads are intended to create the instance and executes the check null == myClass,now both threads have identified instance variable to null thus assume they must create an instance. They sequentially goes to synchronized block and create the instances. At the end, we have two instances in our application.
This can be resolved by simply double check locking. Below code will show you the better way of implementation. Just note- I have used private constructor in code.
public class MyClass {
private final static MyClass myClass = null;
//private constructor
private MyClass(){
}
public static MyClass getInstance() {
if(myClass == null) {
synchronized (MyClass.class){
// Double check
if(myClass == null){
myClass = new MyClass();
}
}
}
return myClass;
}
}
The principle rules which yoy need to take care to define the singleton class is :
Private constructors - which restricts the object creation from other classes
Private static field variable which holds the only instance of the same class
A public static method which is used to return this instance when requested
It depends on how you want it, whether you want early initialization or lazy initialization. The first one is an example of early initialization, while the second one is an example of lazy initialization. There are multiple ways to define a perfect Singleton 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.

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.

mutating object as singleton?

I am not sure, if anyone has asked this question before (If so apologies).
code copied from wikipedia.
public class Singleton {
private static final Singleton instance = new Singleton();
private Singleton() {}
public static Singleton getInstance() {
return instance;
}
}
How it is thread safe? is it(only) because there is no mutating state in this class?
what happens if I modify it like this
public class Singleton {
private static final Singleton instance = new Singleton();
private FancyClass obj1;
private FancyClass obj2;
//feel free to imagine all the getters and setters for obj1 and obj2,
// like getObj1() and so forth
//tricky method
public void doSomething() {
obj1.destroyEnemy();
obj2.destroyFriend();
}
private Singleton() {
obj1 = null;
obj2 = null;
}
public static Singleton getInstance() {
return instance;
}
}
I have no interest in design-patterns discussion, this is the kind of code, I am supposed to maintain. is the above 'singleton' thread safe, assuming that FancyClass is java standard library class.
You're right that the first example is safe only because there is no mutable state.
In the second example, the singleton isn't doing anything to make it threadsafe, whether it's safe depends on if FancyClass is threadsafe. Putting synchronized on the doSomething method would make it threadsafe.
Introducing getters and setters for obj1 and obj2 would also have the potential to create problems, those would have to be synchronized on the same lock as the doSomething method, and you would need locking even if FancyClass is threadsafe, because if different threads are changing things then those changes need to be made visible across threads.
The first code guarantees that all threads that call getInstance() get a reference to the same instance of Singleton.
For your implementation (second example), the same is true for obj1 and obj2, because they're created while the class itself is created and class creation is thread safe (can't be created twice/"in parallel" within the same classloader).
The doSomething() method is not thread safe. Make it synchronized if you need an atomic operation.
The Singleton pattern is not designed to be Thread Safe at all, just to be unique and forbidding creation of additional instances. The only part that is thread safe in you code is the Singleton instantiation private static final Singleton instance = new Singleton(); as it's invoked one time a class loading time.
But effectively, if there's no members in your class modified by a method invked concurently by external systems, your Singleton will be/stay ThreadSafe
About your code -
Since you are making your constructor private it will never be called. So declaring it null there makes no sense. Anyway instance variables are automatically assigned default values.
First of all the 1st code
public class Singleton {
private static final Singleton instance = new Singleton();
private Singleton() {}
public static Singleton getInstance() {
return instance;
}
}
is called Early initialization unlike lazy initialization in which you create instance only when needed. To make it thread safe you need to do the following
public class Singleton {
private static Singleton singleInstance;
private Singleton() {}
public static Singleton getSingleInstance() {
if (singleInstance == null) {
synchronized (Singleton.class) {
if (singleInstance == null) {
singleInstance = new Singleton();
}
}
}
return singleInstance;
}
Example is of lazy initialization but the concept remains the same.

Categories

Resources