diff --git a/docs/instrumentation/tracing-java-interop.md b/docs/instrumentation/tracing-java-interop.md index 8fb5a4347..57e4c1611 100644 --- a/docs/instrumentation/tracing-java-interop.md +++ b/docs/instrumentation/tracing-java-interop.md @@ -152,14 +152,16 @@ import cats.mtl.Local import cats.syntax.flatMap._ import org.typelevel.otel4s.java.context.Context import io.opentelemetry.context.{Context => JContext} -import scala.util.Using def useJContext[F[_]: Sync, A](use: JContext => A)(implicit L: Local[F, Context]): F[A] = Local[F, Context].ask.flatMap { ctx => // <1> - Sync[F].defer { - Sync[F].fromTry { - val jContext: JContext = ctx.underlying // <2> - Using(jContext.makeCurrent())(_ => use(jContext)) // <3> + Sync[F].delay { + val jContext: JContext = ctx.underlying // <2> + val scope = jContext.makeCurrent() // <3> + try { + use(jContext) + } finally { + scope.close() } } } @@ -167,9 +169,9 @@ def useJContext[F[_]: Sync, A](use: JContext => A)(implicit L: Local[F, Context] 1) `Local[F, Context].ask` - get the current otel4s context 2) `ctx.underlying` - unwrap otel4s context and get `JContext` -3) `Using(jContext.makeCurrent())` - activate `JContext` within the current thread and run `use` afterward +3) `jContext.makeCurrent()` - activate `JContext` within the current thread -**Note:** here we use `Sync[F].defer` and `Sync[F].fromTry` to handle the side effects. +**Note:** we use `Sync[F].delay` to handle the side effects. Depending on your use case, you may prefer `Sync[F].interruptible` or `Sync[F].blocking`. Now we can run a slightly modified original 'problematic' example: diff --git a/examples/src/main/scala/PekkoHttpExample.scala b/examples/src/main/scala/PekkoHttpExample.scala index c4c0ee860..dc00b928e 100644 --- a/examples/src/main/scala/PekkoHttpExample.scala +++ b/examples/src/main/scala/PekkoHttpExample.scala @@ -44,7 +44,6 @@ import org.typelevel.otel4s.trace.Tracer import scala.concurrent.Future import scala.concurrent.duration._ -import scala.util.Using /** This example relies on the OpenTelemetry Java agent. To make it work, add * the following settings to your build: @@ -179,10 +178,13 @@ object PekkoHttpExample extends IOApp.Simple { L: Local[F, Context] ): F[A] = Local[F, Context].ask.flatMap { ctx => - Sync[F].defer { - Sync[F].fromTry { - val jContext: JContext = ctx.underlying - Using(jContext.makeCurrent())(_ => use(jContext)) + Sync[F].delay { + val jContext: JContext = ctx.underlying + val scope = jContext.makeCurrent() + try { + use(jContext) + } finally { + scope.close() } } }