ThreadLocal类为什么要加上private static修饰

个人理解:

    首先加不加 private 个人觉得是一种编程规范吧 类中的变量需要用private 来修饰。

    我们知道对于static 修饰的变量在类的装载时候才会被加载,卸载时候才会被释放。如果大量使用不带static 的对象会造成内存的浪费哦。http://www.daiqiyang.com

    看一下ThreadLocal 源码发现 ThreadLocal 实现方式实际上是通过一个静态的map 去保存的。 引用的方式是弱引用 如果我们创建的大量的ThreadLocal 对象, 当虚拟机回收这些对象的时候 也就是key 被回收了 但是 value 还有弱引用指向 这个静态的map 容易造成内存泄漏。 建议如果某个对象 不用了 可以自己remove 调。

static class ThreadLocalMap {

        /**

        * The entries in this hash map extend WeakReference, using

        * its main ref field as the key (which is always a

        * ThreadLocal object).  Note that null keys (i.e. entry.get()

        * == null) mean that the key is no longer referenced, so the

        * entry can be expunged from table.  Such entries are referred to

        * as "stale entries" in the code that follows.

        */

        static class Entry extends WeakReference<ThreadLocal<?>> {

            /** The value associated with this ThreadLocal. */

            Object value;

            Entry(ThreadLocal<?> k, Object v) {

                super(k);

                value = v;

            }

        }

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    ThreadLocal 在设计上就是当前这个线程 本地的 共享的。 看了一下源码ThreadLocal 的实现方式 是 每个Thread 里面 维护一个自己的 ThreadLocalMap

    在这里插入图片描述

    在这个线程初始化的时候 会去new 出这个map

    在这里插入图片描述http://www.daiqiyang.com

    在这里插入图片描述

    这个Map 存储的key 就是你定义ThreadLocal 对象 Value 就是赋的值 因为不是static 的 如果那个对象被new 了 两次的话 一个类的ThreadLocal对象不会在一个相乘里面共享了。

public class ThreadLocalDog {

    ThreadLocal<String> threadLocal=new ThreadLocal<String>();

}

    1

    2

    3

    4

public class ThreadLocalDogStatic {

    static ThreadLocal<String> threadLocal=new ThreadLocal<String>();

}

    1

    2

    3

public class ThreadLocalTest {

    public static void main(String[] args) {

        ThreadLocalDog threadLocalDog=new ThreadLocalDog();

        threadLocalDog.threadLocal.set("小黄");

        ThreadLocalDog threadLocalDog1=new ThreadLocalDog();

        System.out.println(threadLocalDog1.threadLocal.get());

        ThreadLocalDogStatic.threadLocal.set("小static");

        System.out.println(ThreadLocalDogStatic.threadLocal.get());

    }

}

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

输出结果就显而易见了

null

小static

————————————————

版权声明:本文为CSDN博主「CXHC」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。http://www.daiqiyang.com

原文链接:https://blog.csdn.net/u012957549/article/details/103642962

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。