Saturday, 16 February 2019

ThreadLocal

What is ThreadLocal<T> ?

  • This class provides thread-local variables
  • Each thread has its own, independently initialized copy of the variable - unlike other variables defined in the class 
  • These variables can be accessed either by their get or set method
  • ThreadLocal instances are typically private static fields in classes that wish to associate state with a thread (e.g., a user ID or Transaction ID)
Syntax

ThreadLocal<T> threadLocalValue = new ThreadLocal<>();

How to use ThreadLocal<T> ?

ThreadLocal provides us with four methods


  1. initialValue
    • accessibility - protected
    • return Type - T
      If the thread local variable has been initialized as an Integer
      ThreadLocal<Integer> threadLocalValue = new ThreadLocal<>();
      Then the return type would be Integer
    • No parameters
    • Usage
      • if a programmer wants to set an initial value (at the time of the object being initialized) this method would need to be overriden (by default it returns null)
      • This method is at most called once
        • either at time of initialization
        • when the get method is called the first time, it internally calls this method to fetch the value (might be returned as null - the default value)
        • if the set method is invoked, then the method initialValue will not be called
    • 
      
      private static final AtomicInteger nextId = new AtomicInteger(0);
      private static final
      ThreadLocal<Integer> threadId = new ThreadLocal<Integer>() { @Override protected Integer initialValue() { return nextId.getAndIncrement(); } };
    • Alternate way to initialize the default value is by calling the static method withInitial - this takes input a Supplier to determine its initialValue

      private static final AtomicInteger nextId = new AtomicInteger(0);

      private static final ThreadLocal<Integer> threadId =
              ThreadLocal.withInitial(() -> nextId.getAndIncrement());
      
      
      
  2.  get
    • accessibility - public
    • return Type - T - similar to intialValue
    • No parameters
    • Usage
      • it returns the value of the current threads thread local variable
      • if no value has been set, then the method initialValue is invoked - which may either return the default value - null or the value set during initialization
    • threadId.get();
      
      
  3. set
    • accessibility - public
    • return Type - void
    • One Parameter - type T
    • Usage
      • to set the value for the current threads thread local variable
      • if we are setting a value by overriding the method initialValue, then we might not need this method to set the value, but depends on the use case at hand
    • threadId.set(1);
      
      
  4. remove
    • accessibility - public
    • return Type - void
    • No parameter
    • Usage
      • removes the value of the current threads thread local variable
      • if we try and get the value, then the method initialValue would be invoked to fetch the default value
    • threadId.remove();

How ThreadLocal internally works

ThreadLocal internally uses a Map to (ThreadLocalMap) store
  • Key - the threadLocal variable
  • Value - the value associate to the threadLocal Variable
This threadlocalMap is encapsulated inside the ThreadLocal class and is not accessible outside of it

For working examples, please refer to the below github repository
https://github.com/omerhashmininjago/java-programs/tree/master/src/main/java/com/demonstrate/concepts/threadlocal

No comments:

Post a Comment

Volatile keyword, Synchronized keyword and Lock interface

Volatile Marking a member variable as volatile, makes sure, when ever the member variable is accessed, its value is always read from the...