When and how should I use a ThreadLocal variable?

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

When should I use a ThreadLocal variable?

How is it used?

25条回答
  •  孤街浪徒
    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 connectionHolder
               = new ThreadLocal() {
          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.

提交回复
热议问题