A thread-local variable is one whose value at any one time is linked to which thread it is being accessed from. In other words, it has a separate value per thread. Each thread maintains its own, separate map of thread-local variable values.
These information is passed to various method to retrieve desired value. For example in Struts execute method passes HttpServletRequest and HttpServletResponse, what if we want the instance of ServletContext? we have to change the method signatore to pass ServletContext. One can use ThreadLocal to keep certain objects/values available throught the thread execution.
To create a thread-local variable, you instantiate an object of class ThreadLocal. The ThreadLocal class behaves much like the various Reference classes in java.lang.ref; it acts as an indirect handle for storing or retrieving a value.
The ThreadLocal interface
public class ThreadLocal {
public Object get();
public void set(Object newValue);
public Object initialValue();
}
The get() accessor retrieves the current thread's value of the variable; the set() accessor modifies the current thread's value. The initialValue() method is an optional method that lets you set the initial value of the variable if it has not yet been used in this thread; it allows for a form of lazy initialization.
ThreadLocal offers a number of benefits. It is often the easiest way to render a stateful class thread-safe, or to encapsulate non-thread-safe classes so that they can safely be used in multithreaded environments. Using ThreadLocal allows us to bypass the complexity of determining when to synchronize in order to achieve thread-safety, and it improves scalability because it doesn't require any synchronization. In addition to simplicity, using ThreadLocal to store a per-thread-singleton or per-thread context information has a valuable documentation perk -- by using a ThreadLocal, it's clear that the object stored in the ThreadLocal is not shared between threads, simplifying the task of determining whether a class is thread-safe or not.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment