Passing context to another thread

I am using the 1.42.0 java agent.

I am working on an app that uses an unsupported threading library. Based on reading some posts here, we decided to use the OTel library like this:

import io.opentelemetry.api.trace.Span;

public class MyRunnable implement Runnable {
  private Span span;

  public MyRunnable() {
    this.span = Span.current();
  }

  public void run() {
    try (Scope scope = span.makeCurrent()) {
      // do some backend call here
    }
  }
}

I think the actual Span implementation that gets returned from Span.currentSpan() is co.elastic.apm.agent.opentelemetry.tracing.OTelSpan.

This seems to work ok in the sense that the backend calls are now associated with the trace that was started on a parent thread.

However the stack traces are mixed up. For example, often I will see a span for an Oracle stored proc with stack trace from Apache HttpClient.

Any idea what I'm doing wrong?

thanks

Hi,

Here you capture the current span in the constructor, but you should instead capture and store the Context.current() instead.

Then, when you execute the run() method, you should make the stored context the current one.

The difference here is that due to asynchronous execution the span for which you store a reference might be already ended when you make it current, whereas a context is just a context and just provides the context propagation.

What also needs to be checked here is that all the calls to the constructor are within the expected scope (when there is already a parent span), as the calls to the constructor become caller-sensitive.

Thanks Sylvain. Can you give an example of the last part? I don't know what you mean about checking the expected scope.

What I meant by that is that when the constructor is called Context.current() returns something different than the value of Context.root(), otherwise there is nothing to propagate, and the spans that will be created from that will be top-level spans.

In your application this might be implicit, if you get top-level spans where you expect to have child spans of a parent span, then that could be the issue here.

In short, try it by just propagating the context, I'm probably overthinking what could be wrong here :-).

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.