Home  >  Q&A  >  body text

java - 为什么ThreadLocal 选择在线程中使用成员变量,而不是维护一个以线程为Key,值为value的集合?

阿神阿神2765 days ago441

reply all(4)I'll reply

  • 大家讲道理

    大家讲道理2017-04-18 10:39:44

    By design, ThreadLocal应该依附于Thread的存在而存在,每一个线程都可以有一份空间来存储,所以你说的第2点我非常赞同,至于第1点,我不太看得懂。
    如果按照你的设计,将map放在ThreadLocal,那么这个map得是static的(或者ThreadLocal单例中的成员变量),这样在设计上存在严重问题,这个map will be very difficult to manage:

    1. 试想有没有线程安全问题?
    2. 线程销毁后怎么处理,不做处理这个map将会越来越大?
    

    Design has a set of methods, and even related philosophy, which must be savored carefully.

    reply
    0
  • 黄舟

    黄舟2017-04-18 10:39:44

    At least the one thing I can think of is:

    Reduce the cost of mutual exclusion

    There is a scenario: In order to improve the performance of DateFormat, it is usually combined with ThreadLocal.

    reply
    0
  • 怪我咯

    怪我咯2017-04-18 10:39:44

    Some designs are sometimes not just for performance. You must know that Java pays the most attention to design patterns, and single responsibility is one of the most important principles of design patterns.
    On the other hand, wouldn’t it be faster to directly implement a Map in ThreadLocal than to use Map directly? However, obviously doing so violates single responsibility and makes maintenance more expensive.

    reply
    0
  • 迷茫

    迷茫2017-04-18 10:39:44

    If ThreadLoad directly uses Map<Thread, Object> as the underlying data structure, when a large number of threads use ThreadLocal, first the performance of Map access will decrease. Along with the thread life cycle, the underlying Map needs to frequently add and delete entities. This can easily cause performance bottlenecks.

    reply
    0
  • Cancelreply