singleton with static initializer block - java

Please refer below code and help me to understand why this not a valid singleton implementation.
class A{
private static A ob;
private A(){}
static {
ob = new A();
}
public static A getInstance() {
return ob;
}
}

It is not a valid singleton (multiple instances may be instantiated) because you get the default constructor. Add a private constructor (which will prevent the default constructor from being inserted). And you probably want to override clone().
private A() {
}
#Override
public Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException(this.getClass().getName()
+ ": is a singleton.");
}
I would usually use an enum to implement a singleton.

Nothing stops me creating a new instance of A by calling new A(), so I can have multiple instances of it.

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

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.

Use of a private constructor

I'm a begginer programmer for Android and I found some code over the internet and I couldn't get what this "Class not meant to be instantiated" means?! Also what's the use of it. I would be very happy if somebody could help here.
public class Settings
{
//some code
private Settings() {} // Class not meant to be instantiated
//some code
}
The constructor is private so only the class itself can create instances. There are several reasons for doing this. A couple off the top of my head...
The class is a "utility" class that only contains static methods and so instantiating it would make no sense. As the class is commented "Class not meant to be instantiated" I guess this is the most likely reason.
The class itself controls its own lifecycle and provides methods for creating instances. For example if the class is a lazy singleton it might provide a method that creates an instance when first called and return this instance on subsequent calls.
It is a private constructor. This means that outside classes cannot create new instances using the default constructor.
A little more info
All Objects in Java have a default constructor:
public MyObject() {}
That is how you can have this class:
public class MyObject{}
and still be able to call:
MyObject mObj = new MyObject();
Private Constructors
Sometimes a developer may not want this default constructor to be visible. Adding any other constructor will nullify this constructor. This can either be a declared constructor with empty parameters (with any of the visibility modifiers) or it can be a different constructor all together.
In the case above, it is likely that one of the following models is followed:
The Settings object is instantiated within the Settings class, and is where all the code is run (a common model for Java - where such a class would also contain a static main(String[] args) method).
The Settings object has other, public constructors.
The Settings object is a Singleton, whereby one static instance of the Settings Object is provided to Objects through an accessor method. For example:
public class MyObject {
private static MyObject instance;
private MyObject(){}//overrides the default constructor
public static MyObject sharedMyObject() {
if (instance == null)
instance = new MyObject();//calls the private constructor
return instance;
}
}
This inner construct
private Settings() {}
is a constructor for Settings instances. Since it is private, nobody can access it (outside of the class itself) and therefore no instances can be created.
The constructor is private so its not meant to be called by anything outside of the class
It's not a nested class, it's a constructor. A private constructor means that you can't construct instances of this class from outside, like this:
Settings s = new Settings(); //Compilation error! :(
Now, if a class can't be instantiated, what could it be for? The most likely reason for this is that the class would return instances of itself from a static method, probably as a singleton. The settings are normally global to the program, so a singleton pattern really fits here. So there would be a static method that goes kind of like this
static private TheOnlySettings = null;
static public getSettings()
{
if(TheOnlySettings == null)
TheOnlySettings = new Settings(); //Legal, since it's inside the Settings class
return TheOnlySettings;
}
See if that's indeed the case.
As other have mentioned, a class having private constructors cannot be instantiated from outside the class. A static method can be used in this case.
class Demo
{
private Demo()
{
}
static void createObjects()
{
Demo o = new Demo();
}
}
class Test
{
public static void main (String ...ar)
{
Demo.createObjects();
}
}
We can have private constructor . Below program depicts the use of private constructor with a static function
class PrivateConstructor {
private:
PrivateConstructor(){
cout << "constructor called" << endl;
}
public:
static void display() {
PrivateConstructor();
}
};
int main() {
PrivateConstructor::display();
}

Get instance of subclass with superclass static method

I have a superclass that I would like to forward a static method called getInstance() to all subclasses.
When creating an instance of a subclass, I then register the instance in the superclass (perhaps using a hashtable, where the key is based on getClass()). Then, I wish to use the aforementioned static method ( getInstance ) where the superclass method will return the instance of the correct type.
For example, I have a superclass A, and a subclass B extends A.
I want to write a static method A.getInstance(); when called from B (B.getInstance()), I would like it to return the instance of B that I stored earlier.
Its kinda hard to explain, but I am going to be using this superclass a lot, and I would rather not code a getInstance method into every single subclass.
How would I go about doing something like this?
edit: I just realized that my question may be misconstrued as creating a NEW instance of the object. I have already created the instance, and i wish to get the existing instance of the class
As many others have noted in the comments, what you are trying to do is not possible with static methods. Also, you should try to avoid static methods whenever possible because they can result in a testing and maintanance nightmare (*).
You named your method "getInstance", so I guess what you want to do is a mix of Factory- and Singleton patterns. Here is some information to get you started about these patterns:
Singleton: http://en.wikipedia.org/wiki/Singleton_pattern
Factory Method: http://en.wikipedia.org/wiki/Factory_method_pattern
Abstract Factory: http://en.wikipedia.org/wiki/Abstract_factory
Both should not be coded by hand in these days (*) - Have a look at a good "Dependency Injection" (DI) container like Google Guice or Spring. I am not 100% sure what exactly you want to achieve, but it looks like a DI container will do it for you.
Edit: This is a response to an edit of the question. You want to receive a cached instance of the sub classes. In this case, I would still advise against static methods. You could create a singleton instance of a "BCache" class (using a DI container or programming it by hand), and then use this cache object to look up your registered objects. Using Guice as a DI container, it could look like this (warning, untested):
#Singleton
public class BCache {
private Map<Class<? extends B>, B> cache = ...;
public <T> T getInstance(Class<? extends T> type) {
return (T) cache.get(type);
}
}
I still think it would be possible to get rid of the cache class completely using a DI container, though. Again, this is untested code, using Guice, but it could look like this:
#Singleton
public class A extends B {
public A() {
//I am not sure if you need to register in this case, because your
//DI container keeps track of the singleton instances.
super.register(this);
}
}
public class SomeClassUsingA {
#Inject private A a;
}
(*) Note that "all generalizations are wrong", that is, in some projects it might make sense, but in most it will not.
You can't do exactly what you want with the static methods, in good OOP way. You can can do something with the reflection or bunch of if .. else if.
You however, should use some well defined design patterns like Abstract fectory or Factory method. This is the way you should go, like someone said "Don't invent warm water".
You can always assign a subClass instance to a superClass reference. Therefore your superClass's static methods can set or get a subClass instance. But make sure to cast the returned instance before using.
public class A {
private static A a;
/**
* #param a the a to set
*/
public static void setA(A a) {
A.a = a;
}
/**
* #return the a
*/
public static A getA() {
return a;
}
public class B extends A {
private int index = 0;
/**
* #param index the index to set
*/
public void setIndex(int index) {
this.index = index;
}
/**
* #return the index
*/
public int getIndex() {
return index;
}
Usage:
public static void main(String[] args) throws Exception {
B b = new B();
A.setA(b);
B c = (B) A.getA();
System.out.println(c.getIndex());
}
Change form getInstance() to getInstance(String class)
in the superclass:
public static A getInstance(String class){
if(class.equals("A")){
RegisterObject(...);//User defined method
return new A(...);
}
else if(class.equals("B")){
RegisterObject(...);//User defined method
return new B(...);
}
else if(class.equals("C")){
RegisterObject(...);//User defined method
return new C(...);
}
//... and so on
}
Static methods are cannot know which class is used to invoke them. If for example you have class A and B that extends A and static getInstance() implemented in A there is no difference whether you invoke getInstance() using A or B. Moreover attempt to call B.getIntance() will produce compilation warning (at least in Eclipse).
However you can pass the class as a parameter of getInstance():
public class A {
public static <T extends A> T getInstance(Class<T> clazz) {
return clazz.newInstance(); // I do not catch exceptions here: do it yourself
}
}
public class B extends A {
}
...............
B b = A.getInstance(B.class);
You can do like this way,
class A{
public static A getInstance(){
return new A();
}
#Override
public String toString() {
return "inside A";
}
}
class B extends A{
public static A getInstance(){
return new B();
}
#Override
public String toString() {
return "inside B";
}
}
inside main :
public static void main(String[] args) {
A a1 = A.getInstance();
A a2 = B.getInstance();
System.out.println(a1.toString());
System.out.println(a2.toString());
}

Creating instance in java class

Please advise me the difference between two ways of declaration of java constructor
public class A{
private static A instance = new A();
public static A getInstance() { return instance;
}
public static void main(String[] args) {
A a= A.getInstance();
}
}
AND
public class B{
public B(){};
public static void main(String[] args) {
B b= new B();
}
}
Thanks
Class A is supposed to be a Singleton, where you can only have one instance of A. You retrieve that single instance by calling getInstance();
In software engineering, the singleton
pattern is a design pattern used to
implement the mathematical concept of
a singleton, by restricting the
instantiation of a class to one
object. This is useful when exactly
one object is needed to coordinate
actions across the system.
There are a few ways to go about this depending on your requirements:
public class A{
private static A instance = new A();
private A(){} // private constructor
public static A getInstance() {return instance;}
}
or not creating the instance until the first call
public class A{
private static A instance = null;
private A(){} // private constructor
public static A getInstance() {
if(instance == null){
instance = new A(); // create the one instance.
}
return instance;
}
}
Class B is a class with a no-parameter constructor. You can create as many B instances as you want by calling new B();
It looks like A is an attempt at implementing the singleton pattern, but it's not quite right - it should have a private constructor:
class A {
private static final A INSTANCE = new A();
private A() { }
public static A getInstance() { return INSTANCE; }
}
This ensures that only one instance of A ever exists in your application - if any other object needs to use an instance of A to do something, the only way it can get one is via the getInstance() method, which returns the same instance all the time.
With B, you can have as many instances of B as needed/desired, and any other object is free to make a new instance of B if it chooses.
In the first case, only one instance available. In the second case, one can have as many as possible. You need to make the constructor private in the in the first case.

Categories

Resources