/**
* 懒加载的单例封装
* 支持线程安全
*/
final
public class LazySingleton<T> implements Supplier<T> {
/**
* 创建对象的lambda,不能返回null
*/
private final Supplier<T> creator;
private volatile T instance;
private LazySingleton(Supplier<T> creator) {
this.creator = Objects.requireNonNull(creator);
}
/**
* 获取或创建实例
*/
@Override
public T get() {
T ins = instance;
if (null == ins) {
synchronized (this) {
ins = instance;
if (null == ins) {
ins = creator.get();
if (null == ins) {
throw new IllegalStateException("create instance null");
}
instance = ins;
}
}
}
return ins;
}
/**
* 移除已创建的实例
*/
public T remove() {
T ins = instance;
instance = null;
return ins;
}
//
/**
* @param creator lazy创建对象的lambda,返回值不能为空
*/
public static <T> LazySingleton<T> of(Supplier<T> creator) {
return new LazySingleton<>(creator);
}
}
使用范例
public class Mian3 {
static LazySingleton<Mian3> singleton = LazySingleton.of(Mian3::createS3Client);
public static void main(String[] args) {
Mian3 mian3 = Mian3.singleton.get();
}
public static Mian3 createS3Client() {
return new Mian3();
}
}