ThreadLocal有哪些应用场景?底层如何实现?

1.如何使用?

public class ThreadLocalExample {
    private static final ThreadLocal<String> threadLocal = new ThreadLocal<>();

    public static void main(String[] args) {
        Runnable task = () -> {
            threadLocal.set("Hello from thread " + Thread.currentThread().getName());
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            String value = threadLocal.get();
            System.out.println(value);
            threadLocal.remove();
        };

        Thread thread1 = new Thread(task);
        Thread thread2 = new Thread(task);

        thread1.start();
        thread2.start();
    }
}

2.如何理解?

每个thread线程上有一个threadlocalmap变量,用来存储当前线程的threadlocal数据。

当调用threadlocal的set或get方法时,本质上是操作本线程的threadlocalmap。key用来存储当前threadlocal,value用来存储值。

实际上,threadlocal只是用来操作当前thread线程threadlocalmap的工具类而已,threadlocalmap并不是存储在threadlocal中。

 3.注意哪些问题?

1.内存泄露/溢出:需要手动调用threadlocal.remove()来销毁

4.应用场景有哪些? 

1.多个场景需要用到同一种变量,但每个场景里所用到的变量值不同,需要相互隔离的。

2.隔离线程,存储一些不安全的工具对象。

3.spring中的事物。

4.springMVC中的httpsession,httpservletrequest,httpservletresponse

 

相关推荐

  1. ThreadLocal哪些应用场景底层如何实现

    2024-07-13 19:44:03       22 阅读
  2. ThreadLocal使用的场景哪些

    2024-07-13 19:44:03       18 阅读
  3. React哪些应用场景

    2024-07-13 19:44:03       22 阅读
  4. Redis的应用场景哪些

    2024-07-13 19:44:03       33 阅读
  5. 视觉识别应用场景哪些

    2024-07-13 19:44:03       33 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-13 19:44:03       67 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-13 19:44:03       72 阅读
  3. 在Django里面运行非项目文件

    2024-07-13 19:44:03       58 阅读
  4. Python语言-面向对象

    2024-07-13 19:44:03       69 阅读

热门阅读

  1. IPython:提升Python编程效率的实用技巧与案例

    2024-07-13 19:44:03       19 阅读
  2. 赋值运算符.二

    2024-07-13 19:44:03       18 阅读
  3. 数据结构第25节 深度优先搜索

    2024-07-13 19:44:03       16 阅读
  4. Python面试题:如何在 Python 中发送 HTTP 请求?

    2024-07-13 19:44:03       18 阅读
  5. ThreadLocal使用的场景有哪些?

    2024-07-13 19:44:03       18 阅读
  6. Leetcode(经典题)day1

    2024-07-13 19:44:03       23 阅读
  7. Git:分布式版本控制系统

    2024-07-13 19:44:03       20 阅读
  8. Android Studio下载与安装

    2024-07-13 19:44:03       16 阅读
  9. 搭建项目时前后端的两个注意事项

    2024-07-13 19:44:03       16 阅读