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. Worldview in Context

    Worldview in Context Figures 1 and 2 provide a basis for a deeper understanding of worldview. The se ...

  2. [React] Fix "React Error: Rendered fewer hooks than expected"

    In this lesson we'll see an interesting situation where we're actually calling a function component ...

  3. 搭建java环境时,DOS输入java有反应,javac没反应的解决办法。

    2018-11-12 搭java环境踩了许多坑,之前搭环境时在命令台输入java有反应,javac没反应,后来试了很多方法都一样,然后就把java的所有的环境变量都删了,在控制面板里的卸载程序把所有的 ...

  4. Supercharging your ETL with Airflow and Singer

    转自:https://www.stitchdata.com/blog/supercharging-etl-with-airflow-and-singer/ singer 团队关于singer 与air ...

  5. 小功能 清单模板导入 根据Excel生成树

    把代码备份一下,免得硬盘又坏了,看来已经造成心理阴影了啊. 方式一: //清单范本 public void test1() { //生成说明 var ds = ExcelHelper.ExcelToD ...

  6. uni-app 项目记录

    await等候,等待:期待 什么是async.awaitawait 用于等待异步完成通常async.await都是跟随Promise一起使用的 async返回的都是一个Promise对象同时async ...

  7. Appium-Python-Windows 环境搭建

    目录 1.安装JDK 2.安装Android SDK 3.安装Node.js 4.安装Appium server 5.安装Python 6.安装Appium-Python-Client 7.安装pyt ...

  8. 责任链模式(chainOfResponsibility)

    参考文章:http://wiki.jikexueyuan.com/project/design-pattern-behavior/chain-four.html 定义: 使多个对象都有机会处理请求,从 ...

  9. java集合代码示例

    一.List ArrayList 使用List时,最好初始化容量. ArrayList的默认容量为10,每次扩容增0.5倍,假如要放置100个元素,需要多次扩容. List<String> ...

  10. RabbitMQ C#客户端自动重连

    重要参考文章来源:http://gigi.nullneuron.net/gigilabs/resilient-connections-with-rabbitmq-net-client/ 参考代码:ht ...