ThreadLocal源代码2





private static int nextIndex(int i, int len) {
return ((i + 1 < len) ? i + 1 : 0);
}
private static int prevIndex(int i, int len) {
return ((i - 1 >= 0) ? i - 1 : len - 1);
}

ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
try {
threadLocal.set(new Session(1, "Misout的博客"));
// 其它业务逻辑
} finally {
threadLocal.remove();
}
//还记得Hibernate的session获取场景吗?
private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
//获取Session
public static Session getCurrentSession(){
Session session = threadLocal.get();
//判断Session是否为空,如果为空,将创建一个session,并设置到本地线程变量中
try {
if(session ==null&&!session.isOpen()){
if(sessionFactory==null){
rbuildSessionFactory();// 创建Hibernate的SessionFactory
}else{
session = sessionFactory.openSession();
}
}
threadLocal.set(session);
} catch (Exception e) {
// TODO: handle exception
} return session;
}

















public class MultiThreadDemo {
public static void main(String[] args) throws InterruptedException {
private int value = 0;
Thread increaseThread = new Thread(new Runnable() {
@Override
public void run() {
try {
value = 10;
Thread.sleep(10);
System.out.println("increase value: " + value);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
Thread decreaseThread = new Thread(new Runnable() {
@Override
public void run() {
try {
value = -10;
Thread.sleep(10);
System.out.println("decrease value: " + value);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
increaseThread.start();
decreaseThread.start();
}
}

public class SimpleImpl {
public static void main(String[] args) throws InterruptedException {
private Map<Long, Integer> cacheMap = new HashMap<>();
private int defaultValue = 0 ;
Thread increaseThread = new Thread(new Runnable() {
@Override
public void run() {
long id = Thread.currentThread().getId();
cacheMap.put(id, 10);
Thread.sleep(10);
long id = Thread.currentThread().getId();
if (cacheMap.containsKey(id)) {
return cacheMap.get(id);
}
return defaultValue;
}
});
Thread decreaseThread = new Thread(new Runnable() {
@Override
public void run() {
long id = Thread.currentThread().getId();
cacheMap.put(id, -10);
Thread.sleep(10);
long id = Thread.currentThread().getId();
if (cacheMap.containsKey(id)) {
return cacheMap.get(id);
}
return defaultValue;
}
});
increaseThread.start();
decreaseThread.start();
}
}

public class SimpleImpl2 {
public static class CommonThread extends Thread {
Map<Integer, Integer> cacheMap = new HashMap<>();
}
public static class Number {
public void increase() throws InterruptedException {
Integer id = this.hashCode();
Map<Integer, Integer> cacheMap = (CommonThread) Thread.currentThread().cacheMap;
cacheMap.put(id, 10);
Thread.sleep(10);
return cacheMap.get(id);
}
public void decrease() throws InterruptedException {
Integer id = this.hashCode();
Map<Integer, Integer> cacheMap = (CommonThread) Thread.currentThread().cacheMap;
cacheMap.put(id, -10);
Thread.sleep(10);
return cacheMap.get(id);
}
}
public static void main(String[] args) throws InterruptedException {
final Number number = new Number();
Thread increaseThread = new CommonThread() {
@Override
public void run() {
number.increase();
}
};
Thread decreaseThread = new CommonThread() {
@Override
public void run() {
number.decrease();
}
};
increaseThread.start();
decreaseThread.start();
}
}
在上面的实现中,当线程消亡之后,线程中 cacheMap 也会被回收,它当中存放的副本变量(value)也会被全部回收,并且 cacheMap 是线程私有的,不会出现多个线程同时访问一个 cacheMap 的情况。在 Java 中,ThreadLocal 类的实现就是采用的这种思想,注意只是思想,实际的实现和上面的并不一样。















ThreadLocal源代码2的更多相关文章
- Java ThreadLocal 源代码分析
Java ThreadLocal 之前在写SSM项目的时候使用过一个叫PageHelper的插件 可以自动完成分页而不用手动写SQL limit 用起来大概是这样的 最开始的时候觉得很困惑,因为直接使 ...
- 多线程之美2一ThreadLocal源代码分析
目录结构 1.应用场景及作用 2.结构关系 2.1.三者关系类图 2.2.ThreadLocalMap结构图 2.3. 内存引用关系 2.4.存在内存泄漏原因 3.源码分析 3.1.重要代码片段 3. ...
- ThreadLocal源代码3
public class ThreadLocal1<T> { //当创建了一个 ThreadLocal 的实例后,它的散列值就已经确定了, //threadLocal实例的hashCode ...
- ThreadLocal源代码1
public class ThreadLocalTrxt { static ThreadLocal<Object> x1 = new ThreadLocal<Object>() ...
- 另一鲜为人知的单例写法-ThreadLocal
另一鲜为人知的单例写法-ThreadLocal 源代码范例 当我阅读FocusFinder和Choreographer的时候,我发现这两类的单例实现和我们寻经常使用双重检查锁非常不一样.而是用来一个T ...
- java ThreadLocal(应用场景及使用方式及原理)
尽管ThreadLocal与并发问题相关,可是很多程序猿只将它作为一种用于"方便传參"的工具,胖哥觉得这或许并非ThreadLocal设计的目的,它本身是为线程安全和某些特定场景的 ...
- ThreadLocal分析
我们再介绍一个在多线程环境中经常使用的类ThreadLocal,它是java为解决多线程程序的并发问题提供了一种新的方向,使用这个ThreadLocal类可以帮助开发者很简单地编写出简洁的程序,并且是 ...
- ThreadLocal深入理解与内存泄露分析
ThreadLocal 当使用ThreadLocal维护变量时,ThreadLocal为每个使用该变量的线程提供独立的变量副本.所以每个线程都能够独立地改变自己的副本.而不会影响其他线程所相应的副本. ...
- 深入理解线程本地变量ThreadLocal
ThreadLocal理解: 假设在多线程并发环境中.一个可变对象涉及到共享与竞争,那么该可变对象就一定会涉及到线程间同步操作,这是多线程并发问题. 否则该可变对象将作为线程私有对象,可通过Threa ...
随机推荐
- Blink示例程序
打开Arduino IDE(话说与Processing IDE的UI好像啊 然后将这段代码输入.也可从文件>例子>01.Basics/Blink(File/Examples/01.Basi ...
- 第4章 Spring的数据库开发
4.1 Spring JDBC Spring的JDBC模块负责数据库资源管理和错误处理,化简了开发者对数据库的操作. 4.11 Spring JdbcTemplate的解析 * JdbcTemplat ...
- 17-Flutter移动电商实战-首页_楼层区域的编写
1.楼层标题组件 该组件非常简单,只接收一个图片地址,然后显示即可: class FloorTitle extends StatelessWidget { final String picture_ ...
- Maven配置文件setting.xml详解
注:本文来源于:大话JAVA的那些事 <Maven配置文件setting.xml详解> <?xml version="1.0" encoding="UT ...
- TensorFlow安装笔记(CPU版)
新电脑配环境又出了问题. 先是装了最新版anaconda,python3.7的版本.——2019.10.21 然后conda install TensorFlow,conda install kera ...
- rancher2基础环境配置
一.主机配置 1.配置要求 参考节点要求 2.主机名配置 因为K8S的规定,主机名只支持包含 - 和 .(中横线和点)两种特殊符号,并且主机名不能出现重复. 3.Hosts 配置每台主机的hosts( ...
- rpm 打包:ERROR: No build ID note found in xxxx
网上找修复方法 方法1: define区添加以下这行 %define debug_package %{nil} 参考:https://forums.fedoraforum.org/showthread ...
- bind named.conf 的理解
[root@46 /]#yum -y install bind bind-chroot bind-libs bind-utils caching-nameserver目录说明/var/named/ch ...
- linux 下查看redis是否启动
make make PREFIX=/usr/local/redis install mkdir /etc/redis/ cp redis.conf /etc/redis/ 打开redis.conf文件 ...
- linux下使用clamav排查病毒
clamav wget http://www.clamav.net/downloads/production/clamav-0.102.0.tar.gz ### Installyum -y insta ...