Home > Java > javaTutorial > How to implement the Baohan pattern in java singleton

How to implement the Baohan pattern in java singleton

WBOY
Release: 2023-05-16 21:52:33
forward
1488 people have browsed it

Instructions for use

1. Baohan is the singleton pattern with the most variations.

2. The core of Baohan mode is lazy loading. The advantage is that it starts quickly and saves resources until the instance is accessed for the first time. The small disadvantage of cases that require initialization is that it is troublesome to write. The disadvantage is that the thread is unsafe and the if statement has race conditions.

Example

//饱汉
//UnThreadSafe
public class Singleton1 {
    private static Singletion1 singleton = null;
    
    private Singleton1() {
    }
    
    public static Singleton1 getInstance() {
        if (singleton == null) {
            singleton = new Singleton1();
        }
        return singleton;
    }
}
Copy after login

The above is the detailed content of How to implement the Baohan pattern in java singleton. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template