220. ThreadLocal

Java threads share the same memory, but sometimes we need to have dedicated memory for each thread. Java provides ThreadLocal as an approach for storing and retrieving values for each thread separately. A single instance of ThreadLocal can store and retrieve values of multiple threads. If thread A stores the x value and thread B stores the y value in the same instance of ThreadLocal then, later on, thread A retrieves the x value and thread B retrieves the y value.

Java ThreadLocal is typically used in the following two scenarios:

  • For providing per-thread instances (thread-safety and memory efficiency)

  • For providing per-thread context

Let's take a look at problems for each scenario in the next sections.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
52.15.214.27