When and how should I use a ThreadLocal variable?

前端 未结 25 1934
再見小時候
再見小時候 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.

    0 讨论(0)
  • 2020-11-22 13:00

    Since a ThreadLocal is a reference to data within a given Thread, you can end up with classloading leaks when using ThreadLocals in application servers using thread pools. You need to be very careful about cleaning up any ThreadLocals you get() or set() by using the ThreadLocal's remove() method.

    If you do not clean up when you're done, any references it holds to classes loaded as part of a deployed webapp will remain in the permanent heap and will never get garbage collected. Redeploying/undeploying the webapp will not clean up each Thread's reference to your webapp's class(es) since the Thread is not something owned by your webapp. Each successive deployment will create a new instance of the class which will never be garbage collected.

    You will end up with out of memory exceptions due to java.lang.OutOfMemoryError: PermGen space and after some googling will probably just increase -XX:MaxPermSize instead of fixing the bug.

    If you do end up experiencing these problems, you can determine which thread and class is retaining these references by using Eclipse's Memory Analyzer and/or by following Frank Kieviet's guide and followup.

    Update: Re-discovered Alex Vasseur's blog entry that helped me track down some ThreadLocal issues I was having.

    0 讨论(0)
  • 2020-11-22 13:00

    [For Reference]ThreadLocal cannot solve update problems of shared object. It is recommended to use a staticThreadLocal object which is shared by all operations in the same thread. [Mandatory]remove() method must be implemented by ThreadLocal variables, especially when using thread pools in which threads are often reused. Otherwise, it may affect subsequent business logic and cause unexpected problems such as memory leak.

    0 讨论(0)
  • 2020-11-22 13:05

    The ThreadLocal class in Java enables you to create variables that can only be read and written by the same thread. Thus, even if two threads are executing the same code, and the code has a reference to a ThreadLocal variable, then the two threads cannot see each other's ThreadLocal variables.

    Read more

    0 讨论(0)
  • 2020-11-22 13:07

    In Java, if you have a datum that can vary per-thread, your choices are to pass that datum around to every method that needs (or may need) it, or to associate the datum with the thread. Passing the datum around everywhere may be workable if all your methods already need to pass around a common "context" variable.

    If that's not the case, you may not want to clutter up your method signatures with an additional parameter. In a non-threaded world, you could solve the problem with the Java equivalent of a global variable. In a threaded word, the equivalent of a global variable is a thread-local variable.

    0 讨论(0)
  • 2020-11-22 13:09

    Thread-local variables are often used to prevent sharing in designs based on mutable Singletons or global variables.

    It can be used in scenarios like making seperate JDBC connection for each thread when you are not using a Connection Pool.

    private static ThreadLocal<Connection> connectionHolder
               = new ThreadLocal<Connection>() {
          public Connection initialValue() {
               return DriverManager.getConnection(DB_URL);
              }
         };
    
    public static Connection getConnection() {
          return connectionHolder.get();
    } 
    

    When you call getConnection, it will return a connection associated with that thread.The same can be done with other properties like dateformat, transaction context that you don't want to share between threads.

    You could have also used local variables for the same, but these resource usually take up time in creation,so you don't want to create them again and again whenever you perform some business logic with them. However, ThreadLocal values are stored in the thread object itself and as soon as the thread is garbage collected, these values are gone too.

    This link explains use of ThreadLocal very well.

    0 讨论(0)
提交回复
热议问题