Avinash Jethy
Avinash Jethy

Reputation: 87

What is the use of ThreadLocal?

What is the use of ThreadLocal when a Thread normally works on variable keeping it in its local cache ?

Which means thread1 do not know the value of same var in thread2 even if no ThreadLocal is used .

Upvotes: 4

Views: 2570

Answers (3)

ZhongYu
ZhongYu

Reputation: 19682

It's kind of a global variable for the thread itself, so that any code running in the thread can access it directly. (A "really" global variable can be accessed by any code running in the "process"; we could call it ProcessLocal:)

Is global variable bad? Maybe; it should be avoided if we can. But sometimes we have no choice, we cannot pass the object through method parameters, and ThreadLocal proves to be useful in many designs without causing too much trouble.

Upvotes: 3

yshavit
yshavit

Reputation: 43391

A thread doesn't have to keep variables in its local cache -- it's just that it's allowed to, unless you tell it otherwise.

So:

  • If you want to force a thread to share its state with other threads, you have to use synchronization of some sort (including synchronized blocks, volatile variables, etc).
  • If you want to prevent a thread from sharing its state with other threads, you have to use ThreadLocal (assuming the object that holds the variable is known to multiple threads -- if it's not, then everything is thread-local anyway!).

Upvotes: 5

Jon Skeet
Jon Skeet

Reputation: 1500525

With multiple threads, although you have to do work to make sure you read the "most recent" value of a variable, you expect there to be effectively one variable per instance (assuming we're talking about instance fields here). You might read an out of date value unless you're careful, but basically you've got one variable.

With ThreadLocal, you're explicitly wanting to have one value per thread that reads the variable. That's typically for the sake of context. For example, a web server with some authentication layer might set a thread-local variable early in request handling so that any code within the execution of that request can access the authentication details, without needing any explicit reference to a context object. So long as all the handling is done on the one thread, and that's the only thing that thread does, you're fine.

Upvotes: 7

Related Questions