pcyuen98 / covidAngular

0 stars 0 forks source link

Usage of thread local and 3 examples #25

Closed nrnh closed 3 years ago

nrnh commented 3 years ago

ThreadLocal

ThreadLocal is used to create variables that can only be read and write by the same thread. If two threads are executing the same code and that code has a reference to a ThreadLocal variable then the two threads can't see the local variable of each other.

image

1. Create a ThreadLocal: This only needs to be done once per thread. Multiple threads can now get and set values inside this ThreadLocal. ThreadLocal threadLocal = new ThreadLocal();

2. Set ThreadLocal value: threadLocal.set("thread 1");

3. Get ThreadLocal value: String thread1 = threadLocal.get();

4. Remove ThreadLocal value threadLocal.remove();

Example: image

Result: image

5. ThreadLocal with initial value The initialValue() method returns the current thread's initial value for this thread-local variable.

Example: image

Result: image

Another way to do it is by using withInitial() and passing a supplier to it Example: image

Result: image

nrnh commented 3 years ago

Example of how ThreadLocal can be use

  1. Spring framework uses ThreadLocal for managing transactions behind the scenes by keeping these connection objects in ThreadLocal variables. At high level, when a transaction is started it gets the connection ( and disables the auto commit ) and keeps it in ThreadLocal. On further db calls it uses same connection to communicate with db.
  2. SimpleDateFormat is not thread safe because it stores intermediate results in instance fields. If one instance is used by two threads they can mess each other's results. ThreadLocal can be use to make it thread-safe.
  3. Using static ThreadLocal to hold the transaction context: when framework code needs to determine what transaction is currently running, it fetches the transaction context from this ThreadLocal. Ex: storing user-specific context data per user id.
nrnh commented 3 years ago

References:

  1. https://stackoverflow.com/questions/817856/when-and-how-should-i-use-a-threadlocal-variable?answertab=oldest#tab-top
  2. https://www.javatpoint.com/java-threadlocal/class#:~:text=Java%20ThreadLocal%20class%20provides%20thread,local%20variable%20of%20each%20other.
  3. https://www.youtube.com/watch?v=a_BoqsnVR2U
  4. https://medium.com/javarevisited/java-concurrency-threadlocal-c1b18ab8e488