Example of Singleton in Java

By Arvind Rai, November 14, 2023

Creating Singleton Class

A singleton class is a class of which only one object can be created. To create such class, follow the steps:

1. Create constructor private. This will stop outer class to create object directly.
2. Provide a static method to get instance of that class.
3. Inside static method, create the object of the class surrounded by synchronized block.
4. If class implements Cloneable, then we need to override clone method to throw exception.
5. If class implements Serializable, we need to implement readResolve method.

Example

If we are creating a complete Singleton class, we need to take care the serialization of singleton class. readResolve is the method which returns the instance of the class when a serialized class is deserialized. So implement the readResolve method to return the same object.

Find the complete example of singleton.
SingletonDemo.java
package com.concretepage;
import java.io.ObjectStreamException;
import java.io.Serializable;
public class SingletonDemo implements Cloneable, Serializable {
    private static final long serialVersionUID = 1L;
    private static SingletonDemo singleton = null;
    private SingletonDemo() {
    }
    public static SingletonDemo getInstance() {
        if (singleton == null) {
            synchronized (SingletonDemo.class) {
                if (singleton == null) {
                    singleton = new SingletonDemo();
                }
            }
        }
        return singleton;
    }
    @Override
    public Object clone() throws CloneNotSupportedException {
        throw new CloneNotSupportedException();
    }
    private Object readResolve() throws ObjectStreamException {
        return singleton;
    }
}
POSTED BY
ARVIND RAI
ARVIND RAI
LEARN MORE








©2024 concretepage.com | Privacy Policy | Contact Us