Friday 7 August 2015

ThreadLocal in Java

ThreadLocal is way to maintain the Thread Confinement.

What is Thread Confinement ?..
 How data can be accessed from a single thread. When an Object is confined to a thread, then usage is thread safe even if the confined object itself is not thread safe.

ThreadLocal provides facility that How an object can be bind to a thread, and multiple threads will not be able to see other thread's confined object . Once thread gets killed or done with its job then bind object instance will also be eligible for garbage collection.






                                 Thread-local variables are used to prevent sharing in design. To understand the usage of ThreadLocal, Lets take an example, Suppose you have an Application that exposes RESTful services. In this application each request is new/independent request i.e request is not depend on the previous request or session. Suppose Once you get the request you have to do validation and send request to another class say 'A' for further processing, A is design to  perform some business logic based on the request. Once A done with its work the call another class 'C', which is responsible to interact with DB.
            In the above example, There is a variable  which is required by some of the classes for processing but not for all the class. One way is to pass this variable in each 'n' every class. This approach is a bad design where each class has to carry this variable just for passing. What if we have multiple variables, we can not pass multiple variables to each and every until those are required by all the classes. Another approach is, We can create a ThreadLocal which can store  all the variables, those are required by multiple classes.Any class can set the variable in the ThreadLocal and get the variables from ThreadLocal.

ThreadLocal provides get and set accessor methods that maintain a separate copy of the value for each thread that uses it, So a get returns the most recent value passed to set from the currently executing thread. To understand the ThreadLocal<T>  is as holding a Map<Thread,T> that store Thread specific values.






Code Example:

import java.util.HashMap;
public class LocalCache extends HashMap<String, String> {
    private static final long serialVersionUID = 1L;
  
    private static final ThreadLocal<LocalCache> cache =
            new ThreadLocal<LocalCache>() {
                    public LocalCache initialValue() {
                        return new LocalCache();
                        }
                };

    public static LocalCache getLocalCache() {
        return cache.get();

    }

}



Any class can set the variable in cache and get it from the cache. This cache is bound to a thread and cannot be corrupt by other thread. When a thread calls ThreadLocal.get for the first time, intialValue is requested to provide the initial value for that thread.

How to set the variable:
LocalCache.getLocalCache().put("name", "abc");

Any class can retrieve this variable using below command.
LocalCache.getLocalCache().get("name");








No comments:

Post a Comment