What is ThreadLocal class? How can it be used | Eklavya Online

What is ThreadLocal class? How can it be used

Below are some key points about ThreadLocal variables

  • A thread-local variable effectively provides a separate copy of its value for each thread that uses it.
  • ThreadLocal instances are typically private static fields in classes that wish to associate state with a thread
  • In case when multiple threads access a ThreadLocal instance, separate copy of Threadlocal variable is maintained for each thread.
  • Common use is seen in DAO pattern where the DAO class can be singleton but the Database connection can be maintained separately for each thread. (Per Thread Singleton)
  • ThreadLocal variable are difficult to understand and I have found below reference links very useful in getting better understanding on them
  • “http://www-128.ibm.com/developerworks/java/library/j-threads3.html”Good article on ThreadLocal on IBM DeveloperWorks
  • “http://javaboutique.internet.com/tutorials/localdata”Managing data : Good example
  • href=”http://java.sun.com/j2se/1.4.2/docs/api/java/lang/ThreadLocal.html”Refer Java API Docs