在不加锁的情况下,实现一个线程安全的单例模式

本文深入探讨了单例模式的多种实现方式,包括饿汉式、懒汉式、静态内部类和枚举类,对比了它们的优劣及适用场景。同时,介绍了使用CAS技术实现无锁并发,确保线程安全的单例模式,分析了其原理和潜在问题。

第一、单例模式的几种实现方式
a.饿汉式(线程安全,调用效率高,但是不能延时加载)

/**
 * 单例模式
 * @author shixiangcheng
 * 2019-07-21
 */
public class Singleton {
    private static final Singleton singleton=new Singleton();
    private Singleton(){
    	System.out.println("==");
    }
    public static Singleton getInstance(){
    	return singleton;
    }
}

b.懒汉式(线程安全,调用效率不高,但是能延时加载)

/**
 * 单例模式
 * @author shixiangcheng
 * 2019-07-21
 */
public class Singleton {
    private static Singleton singleton=null;
    private Singleton(){
    	System.out.println("==");
    }
    //方法同步,调用效率低
    public static synchronized Singleton getInstance(){
        if(singleton==null){
        	singleton=new Singleton();
        }
        return singleton;
    }
}

c.静态内部类实现模式(线程安全,调用效率高,可以延时加载)

/**
 * 单例模式
 * @author shixiangcheng 
 * 2019-07-21
 */
public class Singleton {
	private Singleton() {System.out.println("create instance");}
	private static class SingletonClassInstance {
		private static final Singleton singleton = new Singleton();
	}
	public static Singleton getInstance() {
		return SingletonClassInstance.singleton;
	}
}

d.枚举类(线程安全,调用效率高,不能延时加载,可以天然的防止反射和反序列化调用)

/**
 * 单例模式
 * @author shixiangcheng 
 * 2019-07-21
 */
public enum Singleton {
	//枚举元素本身就是单例
	INSTANCE;
	//添加自己需要的操作
	public void singletonOperation(){
		System.out.println("do");
	}
}

-单例对象 占用资源少,不需要延时加载,枚举 好于 饿汉
-单例对象 占用资源多,需要延时加载,静态内部类 好于 懒汉式

以上几种答案,其实现原理都是利用借助了类加载的时候初始化单例。即借助了ClassLoader的线程安全机制。
所谓ClassLoader的线程安全机制,就是ClassLoader的loadClass方法在加载类的时候使用了synchronized关键字。也正是因为这样, 除非被重写,这个方法默认在整个装载过程中都是同步的,也就是保证了线程安全。
所以,以上各种方法,虽然并没有显示的使用synchronized,但是还是其底层实现原理还是用到了synchronized。
第二、使用CAS技术实现无锁并发,保证线程安全。
点此了解CAS技术
CAS是项乐观锁技术,当多个线程尝试使用CAS同时更新同一个变量时,只有其中一个线程能更新变量的值,而其它线程都失败,失败的线程并不会被挂起,而是被告知这次竞争中失败,并可以再次尝试。实现单例的方式如下:

import java.util.concurrent.atomic.AtomicReference;
/**
 * 使用CAS保证线程安全
 * @author shixiangcheng
 * 2019-12-20
 */
public class Singleton {
	private static final AtomicReference<Singleton> INSTANCE=new AtomicReference<Singleton>();
	private Singleton(){}
	public static Singleton getInstance(){
		for(;;){
			Singleton singleton=INSTANCE.get();
			if(singleton!=null){
				return singleton;
			}
			singleton=new Singleton();
			if(INSTANCE.compareAndSet(null, singleton)){
				return singleton;
			}
		}
	}
}

用CAS的好处在于不需要使用传统的锁机制来保证线程安全,CAS是一种基于忙等待的算法,依赖底层硬件的实现,相对于锁它没有线程切换和阻塞的额外消耗,可以支持较大的并行度。
CAS的一个重要缺点在于如果忙等待一直执行不成功(一直在死循环中),会对CPU造成较大的执行开销。
另外,如果N个线程同时执行到singleton = new Singleton();的时候,会有大量对象创建,很可能导致内存溢出。

如果觉得对您有帮助,请帮忙点赞。老师说,点赞的人最美丽。

### 三、C++中线程安全单例模式实现方法 在C++中实现线程安全单例模式,通常有以下几种方式: #### 饿汉式(静态变量初始化) 这种方法在程序启动时就创建实例,避免了多线程问题。由于是静态变量初始化,因此天然线程安全。 ```cpp class Singleton { public: static Singleton& getInstance() { static Singleton instance; return instance; } private: Singleton() {} ~Singleton() {} Singleton(const Singleton&) = delete; Singleton& operator=(const Singleton&) = delete; }; ``` 这种方式的优点是实现简单且线程安全,缺点是无法延迟加载[^4]。 #### 懒汉式(双重检查定) 为了支持延迟加载并保证线程安全,可以使用双重检查定(Double-Checked Locking)技术。通过加锁确保在第一次调用`getInstance()`时只创建一个实例,并避免每次调用都加锁。 ```cpp #include <mutex> class Singleton { public: static Singleton* getInstance() { if (_instance == nullptr) { std::lock_guard<std::mutex> lock(_mtx); if (_instance == nullptr) { _instance = new Singleton(); } } return _instance; } private: Singleton() {} ~Singleton() {} Singleton(const Singleton&) = delete; Singleton& operator=(const Singleton&) = delete; static Singleton* _instance; static std::mutex _mtx; }; Singleton* Singleton::_instance = nullptr; std::mutex Singleton::_mtx; ``` 此方法适用于需要延迟加载的场景,但需要注意内存泄漏问题,应配合资源管理机制(如RAII或智能指针)进行清理[^2]。 #### 使用C++11局部静态变量特性 C++11标准中规定,函数内的局部静态变量初始化是线程安全的。因此可以在`getInstance()`中直接定义静态对象,返回其引用即可实现线程安全的单例。 ```cpp class Singleton { public: static Singleton& getInstance() { static Singleton instance; return instance; } private: Singleton() {} ~Singleton() {} Singleton(const Singleton&) = delete; Singleton& operator=(const Singleton&) = delete; }; ``` 该实现方式简洁、线程安全,是推荐的做法。 #### 使用互斥手动控制(POSIX线程) 在某些情况下可能使用POSIX线程库(pthread)来实现线程同步。例如,在类的静态方法中使用`pthread_mutex_t`来保护实例的创建过程。 ```cpp #include <pthread.h> class Singleton { protected: Singleton() { pthread_mutex_init(&mutex, NULL); } public: static pthread_mutex_t mutex; static Singleton* instance() { pthread_mutex_lock(&mutex); static Singleton obj; pthread_mutex_unlock(&mutex); return &obj; } int a; }; pthread_mutex_t Singleton::mutex; ``` 虽然这种写法能保证线程安全,但在实际开发中较少使用,因为C++标准库提供了更高级别的封装(如`std::mutex`和`std::lock_guard`)[^1]。 --- ###
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值