【推荐】2019 Java 开发者跳槽指南.pdf(吐血整理) >>>
单例模式有两种写法:
1:饿汉模式
优点:饿汉模式天生是线程安全的,使用时没有延迟
缺点:启动时即创建实例,启动慢,有可能造成资源浪费
@Slf4j
public class HungrySingle {
private static HungrySingle hungrySingle = new HungrySingle();
public static HungrySingle getHungrySingle(){
log.info("HungrySingle::getHungrySingle::time:{}",(new Date()).getTime());
return hungrySingle;
}
}
2:懒汉模式
优点:懒加载启动快,资源占用小,使用时才实例化,无锁
缺点:非线程安全
@Slf4j
public class LazySingle {
private static LazySingle lazySingle = null;
public LazySingle() {
}
public static LazySingle getLazySingle(){
if(lazySingle == null){
lazySingle = new LazySingle();
}
return lazySingle;
}
}
2.1:懒汉模式(线程安全且无锁的写法)实际应用种推荐的写法
public class LazeSingleSafe {
/**
* 内部类
* 没有绑定关系,而且只有被调用到才会装载,从而实现了延迟加载
*/
private static class SingleSafe{
//静态初始化器,由JVM来保证线程安全
private static LazeSingleSafe lazeSingleSafe = new LazeSingleSafe();
}
public LazeSingleSafe() {
}
public static LazeSingleSafe getLazeSingleSafe(){
return SingleSafe.lazeSingleSafe;
}
}
来源:oschina
链接:https://my.oschina.net/u/2844743/blog/3145626