Getting rid of ThreadLocals #6584
Replies: 5 comments 20 replies
-
I think "riddled with" is overstating it quite a bit [I see precisely 9 instantiations of ThreadLocals in the entire codebase (outside of tests)]. Almost all of the ThreadLocal usage are local caches, and hence not critical to functionality, just performance. You are free to use a different ContextStorage implementation that doesn't use ThreadLocal if you want to. That's really the only functionally-relevant ThreadLocal that I know of. |
Beta Was this translation helpful? Give feedback.
-
Thanks for answering. Yes, "riddled" might be a bad way to put it. I wanted to say any invocation, even harmless sounding ones may include threadlocals under the hood. Which is a problem, if you want to avoid them. Just now I'm working on a problem where a threadlocal was used in Let me rephrase the problem. Seems to me (correct me if I'm wrong), that the SDK assumes, that a span will run on a single thread. This is probably the case for conventional Java applications, but reactive apps, CompletableFutures, cats-effect, etc. do not generally give you this guarantee. In other words if you want to have a span for |
Beta Was this translation helpful? Give feedback.
-
If your goal is completely avoid the use of ThreadLocals for context storage, you have two options:
Both of these options will involve a lot of work and will be very error prone. I recommend understanding how your framework spawns threads and use our Context utilities to make sure the spawning of them properly propagates the Context into the spawned threads. |
Beta Was this translation helpful? Give feedback.
-
@trask Thank you so much for your response! I see that your snippet uses Context.current() which does call some ThreadLocalStorage. Will that pose some problems? In my case, some Spans will start and end in different threads. |
Beta Was this translation helpful? Give feedback.
-
@trask Right hence my confusion. The methods in Context to create a new Context Object seem to all refer to the ThreadLocal stuff. How to handle the Context lifecycle without the ThreadLocals ? Thank you so much ! |
Beta Was this translation helpful? Give feedback.
-
At this point the SDK is riddled with usages of
ThreadLocal
s. Sometimes this is easier to spot, when usingcurrent()
or similar methods. Sometimes it is implicit and very hard to spot.Using
ThreadLocal
s makes it very difficult and error-prone to use this SDK in reactive designs, when usingCompletableFuture
s, or when using it in Scala with "cats-effect" or similar effect library.I propose that that core library should not use
ThreadLocal
at all. At most it should be a (clearly marked) optional layer on top.Beta Was this translation helpful? Give feedback.
All reactions