Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ThreadLocal vs thread local variable

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.

like image 833
Amit Avatar asked Jan 13 '23 10:01

Amit


1 Answers

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.

like image 195
Thihara Avatar answered Jan 21 '23 11:01

Thihara