博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
ThreadLocal 设计模式浅谈
阅读量:4352 次
发布时间:2019-06-07

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

部分代码:ThreadLocal中 的get方法, 获得的是当前线程相关的对象

/**     * 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类的部分源码:

publicclass 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模式打破了这种依赖, 避免在编程层次之间形成数据依赖。

 

转载于:https://www.cnblogs.com/listened/p/5031478.html

你可能感兴趣的文章
daemon not running; starting now at tcp:5037 adb: CreateFileW 'nul' failed: 系统找不到指定的文件...
查看>>
装配Bean
查看>>
POJ 3624 01背包
查看>>
linux的基本操作(mysql 的基本操作)
查看>>
JS数字计算精度误差的解决方法
查看>>
Http请求帮助类
查看>>
Sharepoint学习笔记---Sandbox Solution-- Full Trust Proxy--开发实例之(2、在Webpart中访问Full Trust Proxy)...
查看>>
计应152班第3小组之讨论话题--软件的产品计划
查看>>
Oracle SQL 树形 查询
查看>>
Synopsys逻辑工艺库
查看>>
异步FIFO总结
查看>>
ETL的思考zz
查看>>
Linux tail 命令详解
查看>>
你会跟谁结婚zz
查看>>
Java线程安全和非线程安全
查看>>
CSS选择器
查看>>
Hadoop Hive概念学习系列之hive的脚本执行(二十)
查看>>
ivy VMware Mac
查看>>
四种方法重置xp系统密码
查看>>
委托与事件
查看>>