Question

I was reading about ThreadLocal class when I came across the below statement by Joshua Bloch multiple times..

“Sleazing” values through callbacks that you don’t control: sometimes you must call a library method that calls back into your package. At this point, you need some context that you were unable to pass to yourself, due to deficiencies in the library. In this rare situation, thread locals can be a lifesaver.

Having a hard time understanding this one..Would appreciate if someone could elaborate and explain

Thanks..Heena

Was it helpful?

Solution

My application calls a library that searches stored data.

That library also has an interface you can implement that tells it how to convert the raw results of a search into the data format that you want.

My implementation of how to convert search results into the objects I want, involves knowing a particular time zone.

So the process is, (A) I call library search method, (B) search method then calls my other piece of code that converts raw results into my format, (C) my conversion requires knowing a timezone. The challenge is how do I make information, the timezone, that I know at point A, available at point C?

Obviously the methods that the library offers don't include passing around a time zone, so I stick it in a ThreadLocal!

OTHER TIPS

Say you call into a third-party function which later on calls back into your code. In your callback you need some context, i.e. to be able to access some variables of your. However, the third-party function is deficient in that it provides no way of passing an object reference through their code into your callback.

What are you to do?

Unfortunately, you don't really have much choice other than to store the context in what is effectively a global variable (oh horror!). ThreadLocal is a slight refinement of the global variable in that multiple threads using this hack won't step onto each other's toes.

Of course, if the callback happens on a different thread than the one calling the third-party function, this technique breaks down.

Also, this technique doesn't scale. If you simultaneously register two callbacks, you'll need two different callback functions and two different global contexts.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top