How to implement java singleton pattern
1. What is the singleton pattern?
Singleton: Ensure that a class has only one instance and provide a global access point to access it.
The singleton pattern is one of the commonly used software design patterns. Its purpose is to ensure that there is only a single instance of a class in the entire application.
For example, when we start the system, we need to load some public configuration information, which is visible and unique throughout the entire life cycle of the application. In this case, we need to design it in singleton mode. Such as: spring container, session factory, cache, database connection pool, etc.
2. How to ensure the uniqueness of the instance
1) Prevent external initialization
2) Instantiate by the class itself 3) Guarantee instantiation once
4) Provide external methods to obtain instances
5) Thread safety
3. Comparison of several simple profit models
(1) Hungry Chinese style
"Because I am hungry, I have to eat immediately without delay", while defining the static private variables of the class Perform instantiation.
public class Singleton { private static final Singleton singleton = new Singleton(); private Singleton() { } public static Singleton getInstance() { return singleton; } }
①Declare static private class variables and instantiate them immediately, ensuring one instantiation
②Private construction to prevent external instantiation (it can be instantiated through reflection, this situation is not considered)
③Provide public The getInstance() method is used to obtain singleton instances externally
Benefits: Thread safety; fast acquisition of instances Disadvantages: Class loading means initializing the instance, memory waste
(2) Lazy style
"This person is lazy, wait for it "Instantiate it when you need it", lazy loading.
public class Singleton { private static Singleton singleton = null; private Singleton() { } public static Singleton getInstance() { if (singleton == null) { singleton = new Singleton(); } return singleton; } }
Advantages: In the method of obtaining the instance, initialize the instance and save system resources
Disadvantages: ①If there is a lot of initialization work when obtaining the instance, the loading speed will slow down and affect the system performance
②Every time Obtaining an instance requires a non-null check, which causes high system overhead. It is not thread-safe. When multiple threads access getInstance() at the same time, multiple instances may be generated. Next, perform a thread-safe transformation on it:
1) Synchronization lock
public synchronized static Singleton getInstance() { if (singleton == null) { singleton = new Singleton(); } return singleton; }
Advantages: Thread safety, Disadvantages: Locking is required every time you obtain an instance, which consumes resources. In fact, as long as the instance has been generated, you do not need to lock it again for subsequent acquisitions
2) Double check lock
public static Singleton getInstance() { if (singleton == null) { synchronized (Singleton.class) { if (singleton == null) { singleton = new Singleton(); } } } return singleton; }
Advantages: Thread safety, double checking, ensuring synchronization only before the instance is initialized, high efficiency Disadvantages: Still judging whether the instance is not empty, consuming certain resources
3) Static inner class
public class Singleton { private Singleton() { } private static class SingletonHolder { private static final Singleton singleton = new Singleton(); } public static Singleton getInstance() { return SingletonHolder.singleton; } }
Advantages: both It avoids the performance loss caused by synchronization and can delay loading
(3) Enumeration
public enum Singleton { INSTANCE; public void init() { System.out.println("资源初始化。。。"); } }
is naturally thread-safe and prevents reflection from generating instances.
4. Advantages and Disadvantages of Singleton Pattern

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.
