Java单例7种测试实践

/**

  • @author :jiaolian

  • @date :Created in 2021-01-10 21:25

  • @description:饿汉单例测试

  • @modified By:

  • 公众号:叫练

*/

public class HungerSignletonTest {

//类初始化会创建单例对象

private static HungerSignletonTest signleton = new HungerSignletonTest();

private HungerSignletonTest(){};

public static HungerSignletonTest getInstance() {

return signleton;

}

public static void main(String[] args) {

//三个线程测试单例,打印hashcode是否一致

new Thread(()->{System.out.println(HungerSignletonTest.getInstance().hashCode()); }).start();

new Thread(()->{System.out.println(HungerSignletonTest.getInstance().hashCode()); }).start();

new Thread(()->{System.out.println(HungerSignletonTest.getInstance().hashCode()); }).start();

}

}

饿汉模式是主动创建对象,如上面程序代码,JDK1.8环境中主线程启动三个线程获取HungerSignletonTest实例的hashcode是否为同一个对象,测试结果如下图所示,所有的hashcode一致证明程序只有一个实例。饿汉单例在类初始化会提前创建对象。缺点:**过早的创建对象需要提前消耗内存资源,我们需要在使用单例对象时再去创建。**下面我们看看懒汉模式代码。

2.懒汉模式 线程不安全


/**

  • @author :jiaolian

  • @date :Created in 2021-01-10 21:39

  • @description:懒汉设计模式测试

  • @modified By:

  • 公众号:叫练

*/

public class LazySignletonTest {

private static LazySignletonTest signleton = null;

private LazySignletonTest(){};

public static LazySignletonTest getInstance() {

if (signleton == null) {

/*try {

//创建对象睡2秒

Thread.sleep(200);

} catch (InterruptedException e) {

e.printStackTrace();

}*/

signleton = new LazySignletonTest();

}

return signleton;

}

public static void main(String[] args) {

//三个线程测试单例

new Thread(()->{System.out.println(LazySignletonTest.getInstance().hashCode()); }).start();

new Thread(()->{System.out.println(LazySignletonTest.getInstance().hashCode()); }).start();

new Thread(()->{System.out.println(LazySignletonTest.getInstance().hashCode()); }).start();

}

}

懒汉模式是需要用到单例才调用getInstance()方法创建对象,看上去没有什么问题,如果放开上面注释语句,在创建对象睡2秒,可能得到的结果如下图所示,三个线程得到的hashcode的值并不一样,说明signleton对象不是单例。在延迟的情况下,所有线程都会进入if条件语句,所以会有如下情况。缺点:非线程安全,我们需要加一把锁。我们将getInstance()方法改造下,public static synchronized LazySignletonTest getInstance(),用synchronized 修饰下,运行程序,三个线程打印hashcode一致。测试一把,大功告成。还没结束呢?你仔细看下synchronized 修饰的是方法,锁力度会比较大,我们只需要在创建实例对象时加锁就可以了,像我们对追求代码优化极致的程序员必须要“扣”到底。下面我们再来看看用synchronized 修饰单例代码块。

3.懒汉加锁模式 线程还是不安全


/**

  • @author :jiaolian

  • @date :Created in 2021-01-10 21:39

  • @description:懒汉设计模式测试

  • @modified By:

  • 公众号:叫练

*/

public class LazySignletonTest {

private static LazySignletonTest signleton = null;

private LazySignletonTest(){};

public static LazySignletonTest getInstance() {

if (signleton == null) {

/*try {

//创建对象睡2秒

Thread.sleep(2000);

} catch (InterruptedException e) {

e.printStackTrace();

}*/

synchronized (LazySignletonTest.class) {

signleton = new LazySignletonTest();

}

}

return signleton;

}

public static void main(String[] args) {

//三个线程测试单例

new Thread(()->{System.out.println(LazySignletonTest.getInstance().hashCode()); }).start();

new Thread(()->{System.out.println(LazySignletonTest.getInstance().hashCode()); }).start();

new Thread(()->{System.out.println(LazySignletonTest.getInstance().hashCode()); }).start();

}

}

单次检测加锁模式第一次判断signleton不为空就加锁创建对象,看上去没有什么问题,如果放开上面代码注释,在创建对象睡2秒,可能得到的结果如下图所示,三个线程得到的hashcode的值并不一样,说明signleton对象不是单例,为什么会这样呢?因为三个线程调用Thread.sleep(2000);会阻塞在创建对象前面,因为三个线程已经判断了signleton等于空,所以都会创建一个新的实例!OK,既然这样,我们就可以在**synchronized 同步代码块再加一次判断了,保证万无一失!这是单例双重检测加锁,非常经典的面试题!**我们把代码修改成双重检测加锁机制,能万无一失吗?下面我们看代码!事实胜于雄辩!

4.双重检测加锁 指令重排序


/**

  • @author :jiaolian

  • @date :Created in 2021-01-10 21:39

  • @description:懒汉设计模式测试

  • @modified By:

  • 公众号:叫练

*/

public class LazySignletonTest {

private static LazySignletonTest signleton = null;

private LazySignletonTest(){};

public static LazySignletonTest getInstance() {

if (signleton == null) {

synchronized (LazySignletonTest.class) {

if (signleton == null) {

signleton = new LazySignletonTest();

}

}

}

return signleton;

}

public static void main(String[] args) {

//三个线程测试单例

new Thread(()->{System.out.println(LazySignletonTest.getInstance().hashCode()); }).start();

new Thread(()->{System.out.println(LazySignletonTest.getInstance().hashCode()); }).start();

new Thread(()->{System.out.println(LazySignletonTest.getInstance().hashCode()); }).start();

}

}

加锁模式第一次判断signleton不为空就加锁创建对象,经过多次测试,hashcode结果一致说明进程中只有一个对象,看上去没毛病!真是这样吗?接下来我们对上面代码再做一次深入测试

5.双重检测加锁 volatile必要性


import java.util.concurrent.CountDownLatch;

/**

  • @author :jiaolian

  • @date :Created in 2021-01-10 21:39

  • @description:没有volatile修饰单例对象测试!

  • @modified By:1.堆分配空间 2.初始化构造函数 3.地址指向

  • 公众号:叫练

*/

public class VolatileLockTest {

private static VolatileLockTest signleton = null;

public int aa;

private VolatileLockTest(){

aa = 5;

};

public static VolatileLockTest getInstance() {

if (signleton == null) {

synchronized (VolatileLockTest.class) {

if (signleton == null) {

signleton = new VolatileLockTest();

}

}

}

return signleton;

}

public static void reset() {

signleton = null;

}

public static void main(String[] args) throws InterruptedException {

//循环三个线程测试单例

while (true) {

CountDownLatch start = new CountDownLatch(1);

CountDownLatch end = new CountDownLatch(100);

for (int i=0;i<100; i++) {

Thread thread = new Thread(()->{

try {

//多线程同时等待

start.await();

} catch (InterruptedException e) {

e.printStackTrace();

}

//获取单例,如果锁aa等于0相当于是new 指令重排序了;

if (VolatileLockTest.getInstance().aa != 5) {

System.out.println(“线程终止”);

System.exit(0);

}

end.countDown();

});

thread.start();

}

start.countDown();

end.await();

reset();

}

}

}

如上代码所示:在主程序中死循环创建多线程并发生成单例对象,定义变量“aa”为了测试new VolatileLockTest();对象是否发生重排,new指令一般在JVM中可以分成3步执行:

  1. 分配空间。堆上开辟空间。

  2. 执行构造函数赋值。调用VolatileLockTest私有构造函数。

  3. 将引用指向对象。将signleton指向新的对象。

jvm为了执行效率,可能将2,3重排,执行顺序可能是1->3->2,当多线程并发,就可能出现“aa”不等于5情况,说明了指令如果发生重排,在多线程情况下导致进程会有多个实例,就不符合单例的情况了,正确的情况是将实例变量用volatile修饰,它能够禁止指令重排,也就说new指令必须按照1->2->3顺序执行,这就是volatile修饰对象变量必要性,详细了解volatile特性,请看文章《volatile,synchronized可见性,有序性,原子性代码证明(基础硬核)》,里面有大量实践代码!

6.静态内部类 被动型创建实例(推荐使用)


/**

  • @author :jiaolian

  • @date :Created in 2021-01-11 15:49

  • @description:静态内部类单例模式

  • @modified By:

  • 公众号:叫练

*/

public class InnerClassSingleton {

private InnerClassSingleton(){};

public static InnerClassSingleton getInstance() {

return InnerClass.innerClassSingleton;

}

最后

自我介绍一下,小编13年上海交大毕业,曾经在小公司待过,也去过华为、OPPO等大厂,18年进入阿里一直到现在。

深知大多数Java工程师,想要提升技能,往往是自己摸索成长,自己不成体系的自学效果低效漫长且无助。

因此收集整理了一份《2024年Java开发全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。

既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,基本涵盖了95%以上Java开发知识点,不论你是刚入门Android开发的新手,还是希望在技术上不断提升的资深开发者,这些资料都将为你打开新的学习之门!

如果你觉得这些内容对你有帮助,需要这份全套学习资料的朋友可以戳我获取!!

由于文件比较大,这里只是将部分目录截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且会持续更新!
长且无助。**

因此收集整理了一份《2024年Java开发全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。

[外链图片转存中…(img-sqPNh02t-1714819193523)]

[外链图片转存中…(img-8hIIWOH9-1714819193523)]

[外链图片转存中…(img-bUzunqlg-1714819193524)]

既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,基本涵盖了95%以上Java开发知识点,不论你是刚入门Android开发的新手,还是希望在技术上不断提升的资深开发者,这些资料都将为你打开新的学习之门!

如果你觉得这些内容对你有帮助,需要这份全套学习资料的朋友可以戳我获取!!

由于文件比较大,这里只是将部分目录截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且会持续更新!

  • 28
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值