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

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

Related

Singleton class in Android application using synchronized initalizer

I need a single instance of one class to be used across my whole Android application.
I am using the following code to achieve this and I want to be sure that doing it like this is correct, thread-safe and doesn't have an impact on performance.
public class MyClass {
private static MyClass instance;
public static synchronized MyClass getInstance() {
MyClass myClass;
synchronized (MyClass.class) {
if (instance == null) {
instance = new MyClass();
}
myClass = instance;
}
return myClass;
}
}
Whenever I need an instance of MyClass in the application, I call:
MyClass.getInstance();
So, I want ot be sure I'm not doing something wrong here, that this approach won't cause any problems down the line of development and if there are any better alternatives.
I think you don't need a second synchronized inside getInstance method and also you need to make MyClass constructor to be private.
public class Singleton {
private static Singleton INSTANCE = null;
// other instance variables can be here
private Singleton() {};
public static synchronized Singleton getInstance() {
if (INSTANCE == null) {
INSTANCE = new Singleton();
}
return INSTANCE;
}
}

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.

Singleton object- In static block or in getInstance(); which should be used

Below are two ways to implement a singleton. What are the advantages and disadvantages of each?
Static initialization:
class Singleton {
private Singleton instance;
static {
instance = new Singleton();
}
public Singleton getInstance() {
return instance;
}
}
Lazy initialization is:
class Singleton {
private Singleton instance;
public Singleton getInstance(){
if (instance == null) instance = new Singleton();
return instance;
}
}
Synchronized Accessor
public class Singleton {
private static Singleton instance;
public static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
lazy load
low perfomance
Double Checked Locking & volatile
public class Singleton {
private static volatile Singleton instance;
public static Singleton getInstance() {
Singleton localInstance = instance;
if (localInstance == null) {
synchronized (Singleton.class) {
localInstance = instance;
if (localInstance == null) {
instance = localInstance = new Singleton();
}
}
}
return localInstance;
}
}
lazy load
high perfomance
JDK should be 1,5 ++
On Demand Holder idiom
public class Singleton {
public static class SingletonHolder {
public static final Singleton HOLDER_INSTANCE = new Singleton();
}
public static Singleton getInstance() {
return SingletonHolder.HOLDER_INSTANCE;
}
}
lazy load
high performance
cant be used for non static class fields
First one is eager initialisation.
eager initialization creates the instance even before it’s being used and that is not the best practice to use.
Second one is Lazy Initialization.
Lazy implementation works fine incase of single threaded environment but when it comes to multithreaded systems, it can cause issues if multiple threads are inside the if loop at the same time. It will destroy the singleton pattern and both threads will get the different instances of singleton class.
Please visit: http://www.journaldev.com/1377/java-singleton-design-pattern-best-practices-with-examples#static-block-initialization for more information
NOTE: static blocks can access only static variables defined outside static block directly. The object you want to restrict to only one instance creation should be static. Your first methods fails during compilation, second method requires you to create the object first Follow this approach:
class Singleton
{
private static Singleton instance;
private Singleton()
{
}
public static Singleton getInstance()
{
if(instance == null)
instance = new Singleton();
return instance;
}
}
Ensure no creation of the object elsewhere, so change the constructor to private
make your class like this
public class Singleton {
private Singleton() {
}
private static Singleton instance;
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
and call it like..
Singleton instance = Singleton.getInstance();
Static initializers cannot throw exceptions and absorb RuntimeExceptions into ClassDefNotFoundException, which does not halt execution. So you could see lots of
ClassDefNotFoundException's in your logs and you might not even realize something is wrong until much later because execution continues.
The 2nd method allows RuntimeExceptions to stop execution.
More details here:
https://twasink.net/2006/07/07/how-not-to-handle-exceptions-from-static-code-block-in-java/
Use static static block if you need some things to be initliazedz when the app starts. In it's own. Like you may want to load some properties from some file and do something useful....etc
static {
instance = new Singleton();
loadStuff();
}
Use lazy initialization
class Singleton {
private Singleton instance;
public Singleton getInstance(){
if (instance == null) instance = new Singleton();
loadStuff()
return instance;
}
}
and loadStuff will only be triggered when the Singleton.getInstance() is first called.

Singleton in singleton

I have a singleton in singleton data structure. Currently my implementation is like below:
public class Singleton {
private Object embInstance;
private Singleton() {
embInstance = new Object();
}
private static class SingletonHolder {
public static final Singleton instance = new Singleton();
}
public static Singleton getInstance() {
return SingletonHolder.instance;
}
public Object getEmbInstance() {
return embInstance;
}
public Object resetEmbInstance() {
embInstance = null;
}
}
My question are:
Does 'private Singleton()' have to be empty or is it OK to add some code in it?
Is this implementation thread-safe with respect to embInstance?
This implementation is not lazy-loading for embInstance. How to implement a thread-safe lazy-loading for embInstance?
Thanks!
it's ok to add some code to your private, no-args constructor.
I believe the SingletonHolder class will only be initialized once, therefore instance will be guaranteed to be assigned exactly once. However, within the Singleton class you have setters and getters that are not synchronized, so you may have some threading issues there wrt embInstance.
thread-safe lazy-loading: same as lazy-loading, but do it inside a synchronized block:
public static Object getInstance() {
if(embInstance == null) {
synchronized(Singleton.class) {
if(embInstance == null) {
embInstance = new Singleton();
}
}
}
return embInstance;
}
Note that this code is both efficient (no synchronization required once your data is initialized) and thread-safe (initialization occurs inside a synchronized block).
Hope that helps.
The synchronized keyword keeps the methods thread-safe. The getEmbInstance() is the standard way to do lazy instantiation.
public class Singleton {
private Object embInstance;
private Singleton() {
}
private static class SingletonHolder {
public static final Singleton instance = new Singleton();
}
public static Singleton getInstance() {
return SingletonHolder.instance;
}
public synchronized Object getEmbInstance() {
if (embInstance == null)
embInstance = new Object();
return embInstance;
}
public synchronized Object resetEmbInstance() {
embInstance = null;
}
}
Not sure, what you mean. It is certainly syntactically acceptable to have code in the Singleton constructor
This is not inherently thread safe. If embInstance is accessed by multiple threads even if it is via getEmbInstance, it will suffer from race conditions. You must use synchronized to access it if you wish for threadsafety.
To implement a thread-safe lazy load, you must have a lock that prevents changes to Singleton. You can just use the instance of Singleton to lock it as such:
synchronized(this)
Also, you don't need SingletonHolder you can just have a public static Singleton instance in the Singleton class itself.
....eh ...isn't that overcomplexifying things? Why have a singleton in a singleton? Why so many classes?
Moreover, you have a method to 'reset' your singleton to null, but none to actually instantiate a new one.
Why not simply:
public class Singleton {
private static Singleton instance;
private Singleton() { }
public static synchronized Singleton getInstance() {
if (instance == null)
instance = new Singleton(); // The "lazy loading" :p
return instance;
}
}
public class A {
A a;
private A() {}
synchronized public static A getOb() {
if (a == null) {
a = new A();
}
return a;
}
}
You should use synchronized for thread-safety in Singleton.

Categories

Resources