大家讲道理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.
黄舟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.
怪我咯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.
迷茫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.