Loading
ThreadLocal Sample

Java Quick Notes

Refresh Your Java - Before Java Interview

We are Agile, believe in less Documentation - Only Quick notes (Java Interview Questions) of Java/J2ee Read more....


Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet

Go to SiteMap

Q)  What is the Use of ThreadLocal ?


Ans)

A thread-local variable effectively provides a separate copy of its value for each thread
that uses it.
Each thread can see only the value associated with that thread, and is unaware
that other threads may be using or modifying their own copies.

Because thread-local variables are implemented through a class, rather than as part of the
Java language itself, the syntax for using thread-local variables is a bit more clumsy than for
language dialects where thread-local variables are built in.

To create a thread-local variable, you instantiate an object of class ThreadLocal. In following
Example "userName" is stored in a ThreadLocal.

Please note this really useful to Cache Some Data per a Request.

public class YourDataHolder {
   private static ThreadLocal dataVariable = new ThreadLocal();
   private static YourDataHolder dataHolderVar ;
   private YourDataHolder() {
   }
   public void storeDataToThreadLocal (String userName) {
    dataVariable.set(userName);
   }
   public String readDataFromThreadLocal ()  {
    if (dataVariable.get() != null) {
        return (String) dataVariable.get();
    }
   }
   public static ServiceVersionHolder getInstance () {
    if (dataHolderVar == null) {
     dataHolderVar = new YourDataHolder();
    }
    return dataHolderVar;
   }
}



Back to top

------------------------- We hope you got necessary Info On -----------------------------------------

ThreadLocal Sample


ThreadLocal Sample

-------------------------------------------------------------------------------------------------------



Face Book
Request for a Mock Interview/Training

Get a PDF

Face Book
Same look (Read) on any device, this is Ads free