博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
【Java高并发最佳实践】线程安全的单实例模式
阅读量:7218 次
发布时间:2019-06-29

本文共 1634 字,大约阅读时间需要 5 分钟。

hot3.png

参考资料:

高并发Java(7):并发设计模式 

 

1.单实例模式的线程安全的两种上佳实践:

public class SQLFactory{	    private Logger logger = LoggerFactory.getLogger(getClass());//Log.getLog(getClass());       /*//old method not thread-safe    private static SQLFactory instance = null;		public static SQLFactory getInstance() {		if (instance == null) {			instance = new SQLFactory();		}		return instance;	}    */    //thread-safe best practice		public static SQLFactory getInstance() {		return SQLHolder.instance;	}    private static class SQLHolder {		private static SQLFactory instance = new SQLFactory();	}        /*//also good thread-safe    volatile private static SQLFactory instance = null;	public static SQLFactory getInstance() {		synchronized (SQLFactory.class) {			if (instance == null) {				instance = new SQLFactory();			}		}		return instance;    }*/}

 

2.测试方法:

import java.util.concurrent.LinkedBlockingQueue;import java.util.concurrent.ThreadPoolExecutor;import java.util.concurrent.TimeUnit;import com.highgo.admin.migrator.controller.SQLFactory;public class TestThreadSafe {	public void doing() {		System.out.println(SQLFactory.getInstance().hashCode());	}	public static void main(String[] args) {		ThreadPoolExecutor threadPool = new ThreadPoolExecutor(4, 8, 101, TimeUnit.SECONDS,				new LinkedBlockingQueue
(2000)); final TestThreadSafe tf = new TestThreadSafe(); for (int i = 0; i < 10; i++) { threadPool.submit(() -> { tf.doing(); }); } } }

3.测试结果:相同的实例哈希值表示始终都是同一个实例。

1090303302

1090303302
1090303302
1090303302
1090303302
1090303302
1090303302
1090303302
1090303302
1090303302

转载于:https://my.oschina.net/liuyuanyuangogo/blog/1627102

你可能感兴趣的文章
c#-冒泡排序-算法
查看>>
IP釋放、清除、以及刷新DNS
查看>>
第二次作业
查看>>
小知识
查看>>
安装Vmware时竟然也会报错,错误信息见图
查看>>
20179311《网络攻防实践》第三周作业
查看>>
Ural 1042 Central Heating
查看>>
css兼容问题大全
查看>>
2018-2019-1 20165324《信息安全系统设计基础》实验五
查看>>
使用 Applet 渲染 jzy3d WireSurface 波动率曲面图
查看>>
9 Web开发——springmvc自动配置原理
查看>>
截取图片
查看>>
Python学习--01入门
查看>>
MySQL联合查询语法内联、左联、右联、全联
查看>>
看牛顿法的改进与验证局部收敛
查看>>
第十篇、自定义UIBarButtonItem和UIButton block回调
查看>>
复分析学习1
查看>>
Java虚拟机笔记(四):垃圾收集器
查看>>
计算机运行命令全集
查看>>
WebSocket 实战
查看>>