-
In our backend service we have a middleware pattern in which we register handlers to a handler chain. These handlers all implement a Handler interface that consists of a In the otel documentation and code, we see the pattern for building a span and registering that span as the current span is something like the following: public doTheFoo():
Span span = tracer.spanBuilder("OurRelevant:Name:Here")
.setParent(Context.current().with(Span.current())
.startSpan();
try (Scope scope = span.makeCurrent()) {
// do whatever work
} catch (Exception e) {
// handle exceptions
} finally {
span.end();
} The Context incoming =
openTelemetry
.getPropagators()
.getTextMapPropagator()
.extract(Context.current(), headers, textMapGetterInstance);
scope = ContextStorage.get().attach(incoming); But this begs the question, how do we store the scope in a thread safe way that allows us to call scope.close() in our What's the best way for us to proceed with this? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 3 replies
-
This is definitely the hardest part of writing instrumentation. If you create a Scope, you must close it on the same thread that it was opened on. How you accomplish that is definitely going to depend very strongly on the threading model of your application server (or whatever framework you're using). There definitely isn't a one-size-fits-all answer to this question, unfortunately. If you can, I recommend putting together an example that could be reviewed by the instrumentation experts. One thing that I will say about your code snippet, though, is that you shouldn't ever need to interact with ContextStorage directly under normal circumstances. Everything you need should be available on the Context interface itself. |
Beta Was this translation helpful? Give feedback.
-
Yes you can think of the MustBeClosed annotation as you need to know what you are doing. If the before and after are guaranteed to be executed on the same thread synchronously, you can ignore that, probably leaving a comment that you verified the threading behavior. |
Beta Was this translation helpful? Give feedback.
This is definitely the hardest part of writing instrumentation. If you create a Scope, you must close it on the same thread that it was opened on. How you accomplish that is definitely going to depend very strongly on the threading model of your application server (or whatever framework you're using).
There definitely isn't a one-size-fits-all answer to this question, unfortunately. If you can, I recommend putting together an example that could be reviewed by the instrumentation experts.
One thing that I will say about your code snippet, though, is that you shouldn't ever need to interact with ContextStorage directly under normal circumstances. Everything you need should be available on t…