ThreadLocal 设计模式浅谈
2015-12-08 23:33
495 查看
部分代码:ThreadLocal中 的get方法, 获得的是当前线程相关的对象
同理,对于 set方法亦是如此
ThreadLocal 是隶属于 Thread的一个变量, Thread类的部分源码:
ThreadLocal 模式至少通过两方面, 做到线程安全:
1, ‘纵向隔离’, 即跟Thread的数据结构有关, 每个线程访问自己独特的ThreadLocalMap。
2,‘横向隔离’, 即同一线程中,不同的ThreadLocal实例操作的对象之间隔离,这有ThreadLocalMap在存储时采用ThreadLocal实例作为key来保证。
ThreadLocal与synchronized两种方式完成线程安全不同之处:
前者是‘用空间换时间’, 后者是‘用时间换空间’。
ThreadLocal最适合的场景:
同一线程中,不同开发层次中共享数据。
使用ThreadLocal模式主要步骤:
1,建立类, 并封装一个静态的ThreadLocal变量, 以做成共享环境。
2,在类中实现get/set 访问静态ThreadLocal变量的静态方法。
使用ThreadLocal模式的好处:
可以对执行逻辑和执行数据进行有效解耦。因为一般情况下,对象之间的协作是通过参数和返回值来进行消息传递。而ThreadLocal模式打破了这种依赖, 避免在编程层次之间形成数据依赖。
/** * Returns the value in the current thread's copy of this * thread-local variable. If the variable has no value for the * current thread, it is first initialized to the value returned * by an invocation of the {@link #initialValue} method. * * @return the current thread's value of this thread-local */ public T get() { Thread t = Thread.currentThread(); ThreadLocalMap map = getMap(t); if (map != null) { ThreadLocalMap.Entry e = map.getEntry(this); if (e != null) return (T)e.value; } return setInitialValue(); }
同理,对于 set方法亦是如此
/** * Sets the current thread's copy of this thread-local variable * to the specified value. Most subclasses will have no need to * override this method, relying solely on the {@link #initialValue} * method to set the values of thread-locals. * * @param value the value to be stored in the current thread's copy of * this thread-local. */ public void set(T value) { Thread t = Thread.currentThread(); ThreadLocalMap map = getMap(t); if (map != null) map.set(this, value); else createMap(t, value); }
ThreadLocal 是隶属于 Thread的一个变量, Thread类的部分源码:
public class Thread implements Runnable { /* ThreadLocal values pertaining to this thread. This map is maintained * by the ThreadLocal class. */ ThreadLocal.ThreadLocalMap threadLocals = null;
ThreadLocal 模式至少通过两方面, 做到线程安全:
1, ‘纵向隔离’, 即跟Thread的数据结构有关, 每个线程访问自己独特的ThreadLocalMap。
2,‘横向隔离’, 即同一线程中,不同的ThreadLocal实例操作的对象之间隔离,这有ThreadLocalMap在存储时采用ThreadLocal实例作为key来保证。
ThreadLocal与synchronized两种方式完成线程安全不同之处:
前者是‘用空间换时间’, 后者是‘用时间换空间’。
ThreadLocal最适合的场景:
同一线程中,不同开发层次中共享数据。
使用ThreadLocal模式主要步骤:
1,建立类, 并封装一个静态的ThreadLocal变量, 以做成共享环境。
2,在类中实现get/set 访问静态ThreadLocal变量的静态方法。
使用ThreadLocal模式的好处:
可以对执行逻辑和执行数据进行有效解耦。因为一般情况下,对象之间的协作是通过参数和返回值来进行消息传递。而ThreadLocal模式打破了这种依赖, 避免在编程层次之间形成数据依赖。
相关文章推荐
- Linux-2.6.38在mini6410上的移植
- leetcode笔记:Word Search
- 点乘和叉乘的区别
- Lunix php 配置Yii2
- 《挑战程序设计竞赛(第2版)》编程报告
- Python常用全局函数记录
- iOS-tableView点击下拉菜单
- 进程间通信(1)——管道和命名管道
- 《挑战程序设计竞赛(第2版)》编程报告
- 利用Ant脚本生成war包的详细步骤
- SceneLib2在Ubuntu 14.04LTS下安装小结
- js监听浏览器关闭事件
- 南阳ACM 题目22:素数求和问题
- 老毛桃PE工具安装32位win7系统ISO镜
- python算法:rangeBitwiseAnd(连续整数的与)
- C++ 类的构造函数
- NAT模式下,虚拟机ping通宿主,宿主无法ping通虚拟机
- Leetcode 第13题Roman to Integer
- Java图形界面编程(一)
- Python 常用模块使用