What is a singleton in Java?

In Java, a singleton refers to a design pattern where a class can only have one instance created. This means that when an instance of a class already exists, creating another instance will return the existing one. Singleton pattern is commonly used for scenarios requiring global access points, resource sharing, and controlling the number of instances.

There are several ways to achieve the singleton pattern:

  1. Hungry-style singleton pattern: an instance object is created when the class is loaded, ensuring that there is only one instance object.
public class Singleton {
    private static Singleton instance = new Singleton();
    
    private Singleton() {}
    
    public static Singleton getInstance() {
        return instance;
    }
}
  1. Lazy initialization singleton pattern: the instance object is only created when needed, ensuring thread safety through double-checked locking.
public class Singleton {
    private static volatile Singleton instance;
    
    private Singleton() {}
    
    public static Singleton getInstance() {
        if (instance == null) {
            synchronized (Singleton.class) {
                if (instance == null) {
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }
}
  1. Singleton pattern with static inner class: Delay the creation of instance object until the static inner class is loaded, ensuring thread safety and lazy loading.
public class Singleton {
    private Singleton() {}
    
    private static class SingletonHolder {
        private static final Singleton instance = new Singleton();
    }
    
    public static Singleton getInstance() {
        return SingletonHolder.instance;
    }
}

The above are three common ways to implement the singleton pattern. Choose the appropriate method based on specific requirements and scenarios.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds