-
What is Thread Local?
Thread Local can be considered as a scope of access, like a request scope or session scope. It’s a thread scope. You can set any object in Thread Local and this object will be global and local to the specific thread which is accessing this object. Global and local!!? Let me explain:
Values stored in Thread Local are global to the thread, meaning that they can be accessed from anywhere inside that thread. If a thread calls methods from several classes, then all the methods can see the Thread Local variable set by other methods (because they are executing in same thread). The value need not be passed explicitly. It’s like how you use global variables.
Values stored in Thread Local are local to the thread, meaning that each thread will have it’s own Thread Local variable. One thread can not access/modify other thread’s Thread Local variables.
When to use ThreadLocal
ThreadLocal is a simple way to have per-thread data that cannot be accessed concurrently by other threads, without requiring great effort or design compromises.
One possible (and common) use is when you have some object that is not thread-safe, but you want to avoid synchronizing access to that object . Instead, give each thread its own instance of the object.
Since a ThreadLocal is a reference to data within a given Thread, you can end up with classloading leaks when using ThreadLocals in application servers using thread pools. You need to be very careful about cleaning up
any ThreadLocals you get() or set() by using the ThreadLocal’s remove() method.
ThreadLocal Class
- get() : Returns the value in the current thread’s copy of this thread-local variable.
- initialValue() : Returns the current thread’s “initial value” for this thread-local variable.
- remove() : Removes the current thread’s value for this thread-local variable.
- set(T value) : Sets the current thread’s copy of this thread-local variable to the specified value.
demo
Context
1 | public class Context { |
MyThreadLocal
1 | public class MyThreadLocal { |
ThreadLocalDemo
1 | public class ThreadLocalDemo extends Thread { |
BusinessService
1 | public class BusinessService { |