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的更多相关文章

  1. Java ThreadLocal 源代码分析

    Java ThreadLocal 之前在写SSM项目的时候使用过一个叫PageHelper的插件 可以自动完成分页而不用手动写SQL limit 用起来大概是这样的 最开始的时候觉得很困惑,因为直接使 ...

  2. 多线程之美2一ThreadLocal源代码分析

    目录结构 1.应用场景及作用 2.结构关系 2.1.三者关系类图 2.2.ThreadLocalMap结构图 2.3. 内存引用关系 2.4.存在内存泄漏原因 3.源码分析 3.1.重要代码片段 3. ...

  3. ThreadLocal源代码3

    public class ThreadLocal1<T> { //当创建了一个 ThreadLocal 的实例后,它的散列值就已经确定了, //threadLocal实例的hashCode ...

  4. ThreadLocal源代码1

    public class ThreadLocalTrxt { static ThreadLocal<Object> x1 = new ThreadLocal<Object>() ...

  5. 另一鲜为人知的单例写法-ThreadLocal

    另一鲜为人知的单例写法-ThreadLocal 源代码范例 当我阅读FocusFinder和Choreographer的时候,我发现这两类的单例实现和我们寻经常使用双重检查锁非常不一样.而是用来一个T ...

  6. java ThreadLocal(应用场景及使用方式及原理)

    尽管ThreadLocal与并发问题相关,可是很多程序猿只将它作为一种用于"方便传參"的工具,胖哥觉得这或许并非ThreadLocal设计的目的,它本身是为线程安全和某些特定场景的 ...

  7. ThreadLocal分析

    我们再介绍一个在多线程环境中经常使用的类ThreadLocal,它是java为解决多线程程序的并发问题提供了一种新的方向,使用这个ThreadLocal类可以帮助开发者很简单地编写出简洁的程序,并且是 ...

  8. ThreadLocal深入理解与内存泄露分析

    ThreadLocal 当使用ThreadLocal维护变量时,ThreadLocal为每个使用该变量的线程提供独立的变量副本.所以每个线程都能够独立地改变自己的副本.而不会影响其他线程所相应的副本. ...

  9. 深入理解线程本地变量ThreadLocal

    ThreadLocal理解: 假设在多线程并发环境中.一个可变对象涉及到共享与竞争,那么该可变对象就一定会涉及到线程间同步操作,这是多线程并发问题. 否则该可变对象将作为线程私有对象,可通过Threa ...

随机推荐

  1. appium环境应该注意问题

    python中的script要加入到环境变量中 pip3 install appium-python-client(安装appium模块通过引入webdriver) 如果pip3不是内部命令解决方法 ...

  2. 获取浏览器名称与版本checkbrowse()

    function checkbrowse() { var ua = navigator.userAgent.toLowerCase(); var is = (ua.match(/\b(chrome|o ...

  3. redux沉思录:基于flux、状态管理、函数式编程的前端状态管理框架

    基于flux和reduce的通信和状态管理机制; 和数据库管理系统一样,redux是一个状态管理系统(或机制). const store = createStore( reducer, compose ...

  4. 学习:Windows API核心DLL文件

    在 Windows 的系统目录中,存在着很多的动态链接库文件(DLL 文件).这些 DLL 文件中包括了 Windows API 函数可执行程序. DLL 将各函数"导出",这样应 ...

  5. minikube 安装试用

    目前使用k8s 要么用的物理机搭建的环境,要么就是使用docker for mac 中kubernetes 的特性,为了本地调试方便,使用下minikube minukube 包含的特性 负载均衡器 ...

  6. 计蒜客 41387.XKC's basketball team-线段树(区间查找大于等于x的最靠右的位置) (The Preliminary Contest for ICPC Asia Xuzhou 2019 E.) 2019年徐州网络赛

    XKC's basketball team XKC , the captain of the basketball team , is directing a train of nn team mem ...

  7. 洛谷P2949题解

    若想要深入学习反悔贪心,传送门. Description: 有 \(n\) 项工作,每 \(i\) 项工作有一个截止时间 \(D_i\) ,完成每项工作可以得到利润 \(P_i\) ,求最大可以得到多 ...

  8. 数据结构HashMap哈希表原理分析

    先看看定义:“散列表(Hash table,也叫哈希表),是根据关键码值(Key value)而直接进行访问的数据结构.也就是说,它通过把关键码值映射到表中一个位置来访问记录,以加快查找的速度. 哈希 ...

  9. shell 编写进度条

    test.sh #!/bin/bash i= bar='' label=("|" "/" "-" "\\") ] do ...

  10. xshell && xftp 下载

    链接:https://pan.baidu.com/s/1aLdgOSshytIYhArkB7tghQ 提取码:fqjb