Top Description Methods
io.opentelemetry.context

public Interface Context

Known Direct Implementers
io.opentelemetry.context.ArrayBasedContext
Imports
com.google.errorprone.annotations.MustBeClosed, java.util.concurrent.Callable, .Executor, .ExecutorService, .ScheduledExecutorService, .TimeUnit, java.util.function.BiConsumer, .BiFunction, .Consumer, .Function, .Supplier, javax.annotation.Nullable

A context propagation mechanism which can carry scoped-values across API boundaries and between threads.

A Context object can be set to the ContextStorage, which effectively forms a scope for the context. The scope is bound to the current thread. Within a scope, its Context is accessible even across API boundaries, through current. The scope is later exited by Scope#close() closing} the scope.

Context objects are immutable and inherit state from their parent. To add or overwrite the current state a new context object must be created and then attached, replacing the previously bound context. For example:

Context withCredential = Context.current().with(CRED_KEY, cred);
withCredential.wrap(new Runnable() {
  public void run() {
     readUserRecords(userId, CRED_KEY.get());
  }
}).run();

Notes and cautions on use:

Context propagation is not trivial, and when done incorrectly can lead to broken traces or even mixed traces. We provide a debug mechanism for context propagation, which can be enabled by setting -Dio.opentelemetry.context.enableStrictContext=true in your JVM args. This will enable a strict checker that makes sure that Scopes are closed on the correct thread and that they are not garbage collected before being closed. This is done with some relatively expensive stack trace walking. It is highly recommended to enable this in unit tests and staging environments, and you may consider enabling it in production if you have the CPU budget or have very strict requirements on context being propagated correctly (i.e., because you use context in a multi-tenant system). For kotlin coroutine users, this will also detect invalid usage of makeCurrent() from coroutines and suspending functions. This detection relies on internal APIs of kotlin coroutines and may not function across all versions - let us know if you find a version of kotlin coroutines where this mechanism does not function.

See Also
StrictContextStorage

Method Summary

Modifier and TypeMethod and Description
public static Context
current()

Return the context associated with the current Scope.

public <V> V
get(ContextKey<V> key)

Returns the value stored in this Context for the given ContextKey, or null if there is no value for the key in this context.

public default Scope
makeCurrent()

Makes this the current context and returns a Scope which corresponds to the scope of execution this context is current for.

public static Context
root()

Returns the root Context which all other Context are derived from.

public static Executor
taskWrapping(Executor executor)

Returns an Executor which delegates to the provided executor, wrapping all invocations of Executor#execute(Runnable) with the current context at the time of invocation.

public static ExecutorService
taskWrapping(ExecutorService executorService)

Returns an ExecutorService which delegates to the provided executorService, wrapping all invocations of ExecutorService methods such as ExecutorService#execute(Runnable) or ExecutorService#submit(Runnable) with the current context at the time of invocation.

public static ScheduledExecutorService
taskWrapping(ScheduledExecutorService executorService)

Returns an ScheduledExecutorService which delegates to the provided executorService, wrapping all invocations of ExecutorService methods such as ExecutorService#execute(Runnable) or ExecutorService#submit(Runnable) with the current context at the time of invocation.

public <V> Context
with(ContextKey<V> k1, V v1)

Returns a new context with the given key value set.

public default Context
with(ImplicitContextKeyed value)

Returns a new Context with the given ImplicitContextKeyed set.

public default Runnable
wrap(Runnable runnable)

Returns a Runnable that makes this the current context and then invokes the input Runnable.

public default <T> Callable<T>
wrap(Callable<T> callable)

Returns a Runnable that makes this the current context and then invokes the input Runnable.

public default Executor
wrap(Executor executor)

Returns an Executor that will execute callbacks in the given executor, making this the current context before each execution.

public default ExecutorService
wrap(ExecutorService executor)

Returns an ExecutorService that will execute callbacks in the given executor, making this the current context before each execution.

public default ScheduledExecutorService
wrap(ScheduledExecutorService executor)

Returns an ScheduledExecutorService that will execute callbacks in the given executor, making this the current context before each execution.

public default <T> Consumer<T>
wrapConsumer(Consumer<T> consumer)

Returns a Consumer that makes this the current context and then invokes the input Consumer.

public default <T, U> BiConsumer<T, U>
wrapConsumer(BiConsumer<T, U> consumer)

Returns a BiConsumer that makes this the current context and then invokes the input BiConsumer.

public default <T, U> Function<T, U>
wrapFunction(Function<T, U> function)

Returns a Function that makes this the current context and then invokes the input Function.

public default <T, U, V> BiFunction<T, U, V>
wrapFunction(BiFunction<T, U, V> function)

Returns a BiFunction that makes this the current context and then invokes the input BiFunction.

public default <T> Supplier<T>
wrapSupplier(Supplier<T> supplier)

Returns a Supplier that makes this the current context and then invokes the input Supplier.

Method Detail

currentback to summary
public static Context current()

Return the context associated with the current Scope.

getback to summary
public <V> V get(ContextKey<V> key)

Returns the value stored in this Context for the given ContextKey, or null if there is no value for the key in this context.

Annotations
@Nullable
makeCurrentback to summary
public default Scope makeCurrent()

Makes this the current context and returns a Scope which corresponds to the scope of execution this context is current for. Context#current() will return this Context until Scope#close() is called. Scope#close() must be called to properly restore the previous context from before this scope of execution or context will not work correctly. It is recommended to use try-with-resources to call Scope#close() automatically.

The default implementation of this method will store the Context in a ThreadLocal. Kotlin coroutine users SHOULD NOT use this method as the ThreadLocal will not be properly synced across coroutine suspension and resumption. Instead, use withContext(context.asContextElement()) provided by the opentelemetry-extension-kotlin library.

Context prevCtx = Context.current();
try (Scope ignored = ctx.makeCurrent()) {
  assert Context.current() == ctx;
  ...
}
assert Context.current() == prevCtx;
Annotations
@MustBeClosed
rootback to summary
public static Context root()

Returns the root Context which all other Context are derived from.

It should generally not be required to use the root Context directly - instead, use Context#current() to operate on the current Context. Only use this method if you are absolutely sure you need to disregard the current Context - this almost always is only a workaround hiding an underlying context propagation issue.

taskWrappingback to summary
public static Executor taskWrapping(Executor executor)

Returns an Executor which delegates to the provided executor, wrapping all invocations of Executor#execute(Runnable) with the current context at the time of invocation.

This is generally used to create an Executor which will forward the Context during an invocation to another thread. For example, you may use something like Executor dbExecutor = Context.wrapTasks(threadPool) to ensure calls like dbExecutor.execute(() -> database.query()) have Context available on the thread executing database queries.

Since
1.1.0
taskWrappingback to summary
public static ExecutorService taskWrapping(ExecutorService executorService)

Returns an ExecutorService which delegates to the provided executorService, wrapping all invocations of ExecutorService methods such as ExecutorService#execute(Runnable) or ExecutorService#submit(Runnable) with the current context at the time of invocation.

This is generally used to create an ExecutorService which will forward the Context during an invocation to another thread. For example, you may use something like ExecutorService dbExecutor = Context.wrapTasks(threadPool) to ensure calls like dbExecutor.execute(() -> database.query()) have Context available on the thread executing database queries.

Since
1.1.0
taskWrappingback to summary
public static ScheduledExecutorService taskWrapping(ScheduledExecutorService executorService)

Returns an ScheduledExecutorService which delegates to the provided executorService, wrapping all invocations of ExecutorService methods such as ExecutorService#execute(Runnable) or ExecutorService#submit(Runnable) with the current context at the time of invocation.

This is generally used to create an ScheduledExecutorService which will forward the Context during an invocation to another thread. For example, you may use something like ScheduledExecutorService dbExecutor = Context.wrapTasks(threadPool) to ensure calls like dbExecutor.execute(() -> database.query()) have Context available on the thread executing database queries.

Since
1.43.0
withback to summary
public <V> Context with(ContextKey<V> k1, V v1)

Returns a new context with the given key value set.

Context withCredential = Context.current().with(CRED_KEY, cred);
withCredential.wrap(new Runnable() {
  public void run() {
     readUserRecords(userId, CRED_KEY.get());
  }
}).run();

Note that multiple calls to with(ContextKey, Object) can be chained together.

context.with(K1, V1).with(K2, V2);

Nonetheless, Context should not be treated like a general purpose map with a large number of keys and values — combine multiple related items together into a single key instead of separating them. But if the items are unrelated, have separate keys for them.

withback to summary
public default Context with(ImplicitContextKeyed value)

Returns a new Context with the given ImplicitContextKeyed set.

wrapback to summary
public default Runnable wrap(Runnable runnable)

Returns a Runnable that makes this the current context and then invokes the input Runnable.

wrapback to summary
public default <T> Callable<T> wrap(Callable<T> callable)

Returns a Runnable that makes this the current context and then invokes the input Runnable.

wrapback to summary
public default Executor wrap(Executor executor)

Returns an Executor that will execute callbacks in the given executor, making this the current context before each execution.

wrapback to summary
public default ExecutorService wrap(ExecutorService executor)

Returns an ExecutorService that will execute callbacks in the given executor, making this the current context before each execution.

wrapback to summary
public default ScheduledExecutorService wrap(ScheduledExecutorService executor)

Returns an ScheduledExecutorService that will execute callbacks in the given executor, making this the current context before each execution.

wrapConsumerback to summary
public default <T> Consumer<T> wrapConsumer(Consumer<T> consumer)

Returns a Consumer that makes this the current context and then invokes the input Consumer.

wrapConsumerback to summary
public default <T, U> BiConsumer<T, U> wrapConsumer(BiConsumer<T, U> consumer)

Returns a BiConsumer that makes this the current context and then invokes the input BiConsumer.

wrapFunctionback to summary
public default <T, U> Function<T, U> wrapFunction(Function<T, U> function)

Returns a Function that makes this the current context and then invokes the input Function.

wrapFunctionback to summary
public default <T, U, V> BiFunction<T, U, V> wrapFunction(BiFunction<T, U, V> function)

Returns a BiFunction that makes this the current context and then invokes the input BiFunction.

wrapSupplierback to summary
public default <T> Supplier<T> wrapSupplier(Supplier<T> supplier)

Returns a Supplier that makes this the current context and then invokes the input Supplier.