When and how should I use a ThreadLocal variable?

前端 未结 25 1968
再見小時候
再見小時候 2020-11-22 12:35

When should I use a ThreadLocal variable?

How is it used?

25条回答
  •  逝去的感伤
    2020-11-22 12:59

    Threadlocal provides a very easy way to achieve objects reusability with zero cost.

    I had a situation where multiple threads were creating an image of mutable cache, on each update notification.

    I used a Threadlocal on each thread, and then each thread would just need to reset old image and then update it again from the cache on each update notification.

    Usual reusable objects from object pools have thread safety cost associated with them, while this approach has none.

提交回复
热议问题