What is difference in ThreadLocal.get/put
and
class ThreadT extends Thread {
private SomeObj obj;
.....
}
I believe, please correct me if I am wrong, this obj will also be different for each thread. i.e., if we are having 5 objects of the ThreadT, we will be having each five of them having different objects of obj.
So if this is the case, then why do we need to have the need to use ThreadLocal
?
Please correct me if I my understanding about either of the two is incorrect.
From the documentation
This class provides thread-local variables. These variables differ from their normal counterparts in that each thread that accesses one (via its get or set method) has its own, independently initialized copy of the variable.
Your approach will work if you are writing classes that are directly going to extend thread. But what about classes that need a ThreadLocal variable but doesn't have direct access to it's Thread instance?
In such cases ThreadLocal is useful. Specially in server environments where you don't directly use the threads most of the time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With