When and how should I use a ThreadLocal variable?

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

When should I use a ThreadLocal variable?

How is it used?

25条回答
  •  深忆病人
    2020-11-22 13:14

    There are 3 scenarios for using a class helper like SimpleDateFormat in multithread code, which best one is use ThreadLocal

    Scenarios

    1- Using like share object by the help of lock or synchronization mechanism which makes the app slow

    2- Using as a local object inside a method

    In this scenario, if we have 4 thread each one calls a method 1000 time then we have
    4000 SimpleDateFormat object created and waiting for GC to erase them

    3- Using ThreadLocal

    if we have 4 thread and we gave to each thread one SimpleDateFormat instance
    so we have 4 threads, 4 objects of SimpleDateFormat.

    There is no need of lock mechanism and object creation and destruction. (Good time complexity and space complexity)

提交回复
热议问题