java - 为什么ThreadLocal 选择在线程中使用成员变量,而不是维护一个以线程为Key,值为value的集合?
阿神
阿神 2017-04-18 10:37:44
0
4
436
阿神
阿神

闭关修行中......

reply all(4)
大家讲道理

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.

黄舟

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.

刘奇

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.

迷茫

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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!