分析一下双重校验锁实现对象单例代码
时间: 2023-03-07 18:42:37 浏览: 76
双重校验锁实现对象单例代码是一种常用的设计模式,旨在确保只有一个实例被创建。它使用了一种叫做双重检查锁定(double-checked locking)的技术,它使用一个互斥量来保护检查单例变量是否为空的操作,以及创建实例的操作。因此,双重校验锁实现对象单例代码能够确保只有一个对象被实例化,并且只有在需要的时候才会实例化。
相关问题
单例如何实现?双重校验实现原理、静态内部类实现原理
单例模式主要是为了确保一个类只有一个实例,其实现方式一般有饿汉式和懒汉式两种。
饿汉式单例模式是在类加载时就创建单例对象,无需任何判断或锁定操作,因此具有线程安全性。实现方式是将单例对象作为静态成员变量直接进行初始化,代码如下:
```
public class Singleton {
private static Singleton instance = new Singleton();
private Singleton() {}
public static Singleton getInstance() {
return instance;
}
}
```
懒汉式单例模式则是在需要使用时才创建单例对象,相比饿汉式更加节约资源。但是需要考虑线程安全问题。常见的实现方式有双重校验和静态内部类。
双重校验利用同步锁保证对象只被创建一次,通过双重判断,减少了锁的开销。代码实现如下:
```
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;
}
}
```
静态内部类实现方式则是将单例对象作为静态成员内部类,并在外部类中提供静态方法获取内部类对象,在需要使用时才进行加载。由于类加载的线程安全性,所以这种方式可以保证对象的线程安全性。代码实现如下:
```
public class Singleton {
private Singleton() {}
private static class SingletonHolder {
private static final Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance() {
return SingletonHolder.INSTANCE;
}
}
```
java 单例模式 三种模式 代码示例
在 Java 中,单例模式一般有以下三种实现方式:
### 1. 懒汉式单例模式
在第一次调用 `getInstance()` 方法时才会创建单例对象。
```java
public class Singleton {
private static Singleton instance;
private Singleton() {
// 防止外部实例化
}
public static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
```
### 2. 饿汉式单例模式
在类加载时就创建单例对象。
```java
public class Singleton {
private static Singleton instance = new Singleton();
private Singleton() {
// 防止外部实例化
}
public static Singleton getInstance() {
return instance;
}
}
```
### 3. 双重校验锁单例模式
使用双重校验锁可以避免多线程环境下的线程安全问题,同时也实现了懒加载的效果。
```java
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;
}
}
```
在双重校验锁单例模式中,使用 `volatile` 关键字可以保证多线程环境下的可见性和有序性,从而避免出现线程安全问题。同时,使用双重判断可以避免不必要的加锁,提高了代码的执行效率。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![xlsx](https://img-home.csdnimg.cn/images/20210720083732.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)