目录
单例模式
代码中有些对象只应该有一个实例,把当前的成员变成类属性负责加载数据到内存的类应该是单例。其中单例模式可以分为饿汉模式和懒汉模式。
饿汉模式
饿汉方式实现,实例的创建出现在 “类加载” 阶段。第一次使用这个类,就会把类加载的 .class 文件加载到内存里。这一模式是没有线程安全问题的。代码如下:
static class Singleton {//饿汉方式实现
//创建一个成员,保存唯一的一个Singleton 实例
private static Singleton instance = new Singleton();
//提供方法获取实例
public static Singleton gerInstance () {
return instance;
}
//把类的构造方法设为 private,防止其他代码再创建实例
private Singleton () { }
}
//外部只能通过getInstance 方法获取到该实例,而无法通过 new 创建。
Singleton s = Singleton.getInstance ();
懒汉模式
懒汉模式的实现,创建实例的时候是第一次使用 getInstace 时。代码如下:
static class Singleton {
private static Singleton instance = null;
public static Singleton getInstance () {
if(instance == null) {
instnace = new Singleton ();//存在线程安全问题
}
return instance;
}
private Singleton () { }
}
在外部需要获取到instance 实例时,调用 getInstance 方法,判断该instance 实例是否为空,如果不为空,那么直接返回,如果为空,就创建一个新的实例返回。但是在if 语句判断比较操作时,操作不是原子的,因此在操作过程中可能会被其他线程抢夺资源,因此可能会创建多个实例。所以需要对 if 语句进行加锁操作,保证操作的原子性。代码如下:
static class Singleton {
private static Singleton instance = null;
public static Singleton getInstance () {
synchronized (Singleton.class) {//加锁操作
if(instance == null) {
instnace = new Singleton ();
}
}
return instance;
}
private Singleton () { }
}
通过以上对 if 语句进行加锁操作,我们可以对操作的原子性得到保证。但是,这样的操作意味着对所有的 getInstance 操作都需要进行加锁和解锁操作,只有第一次创建实例的时候需要进行加锁操作,所以需要对此进行优化。在锁外加入一个 if 语句判断,如果此时的 instance 为空,则直接返回 instance 实例,如果不为空,再进行加锁操作。代码如下:
static class Singleton {
private static Singleton instance = null;
public static Singleton getInstance () {
if(instance == null) {//只是在第一次初始化是进行加锁操作
synchronized (Singleton.class) {//加锁操作
if(instance == null) {
instnace = new Singleton ();
}
}
}
return instance;
}
private Singleton () { }
}
同时也可以对instance 实例进行 volatile 修饰,这样可以保证每次都是从内存中读数据。代码如下:
static class Singleton {
volatile private static Singleton instance = null;//保证每次都是从内存中读数据
public static Singleton getInstance () {
if(instance == null) {//只是在第一次初始化是进行加锁操作
synchronized (Singleton.class) {//加锁操作
if(instance == null) {
instnace = new Singleton ();
}
}
}
return instance;
}
private Singleton () { }
}
以上就是两种单例模式的讲述,在编写代码的同时也要明白操作的时机和进行优化的原因。