OpenTelemetry Context propagation mechanism for carrying scoped values across API boundaries and between threads in Java applications
—
Core context management provides the fundamental operations for creating, storing, and retrieving contextual information within applications. Context objects are immutable and form parent-child relationships when new values are added.
Retrieves the context associated with the current scope.
static Context current();Returns the context from the current thread's context storage. If no context has been attached, returns the root context.
Usage Example:
// Get current context
Context currentCtx = Context.current();
// Check if a value exists
String userId = currentCtx.get(USER_ID_KEY);
if (userId != null) {
processUser(userId);
}Returns the root context from which all other contexts derive.
static Context root();Generally you should use Context.current() instead. Only use root context when you need to explicitly disregard the current context.
Usage Example:
// Start fresh with root context (rare usage)
Context rootCtx = Context.root();
Context newCtx = rootCtx.with(USER_ID_KEY, "admin");Retrieves a value stored in the context for the given key.
<V> V get(ContextKey<V> key);Parameters:
key - The context key to look upReturns: The value associated with the key, or null if not present
Usage Example:
private static final ContextKey<String> REQUEST_ID_KEY = ContextKey.named("requestId");
Context context = Context.current();
String requestId = context.get(REQUEST_ID_KEY);
if (requestId != null) {
logger.info("Processing request: {}", requestId);
}Creates a new context with the given key-value pair added.
<V> Context with(ContextKey<V> key, V value);Parameters:
key - The context key to store the value undervalue - The value to storeReturns: A new Context containing the key-value pair
Usage Example:
private static final ContextKey<User> USER_KEY = ContextKey.named("user");
// Create new context with user information
User currentUser = getCurrentUser();
Context contextWithUser = Context.current().with(USER_KEY, currentUser);
// Chain multiple values
Context enrichedContext = contextWithUser
.with(REQUEST_ID_KEY, "req-123")
.with(TENANT_KEY, "tenant-456");Creates a new context with an implicit context keyed value.
Context with(ImplicitContextKeyed value);Parameters:
value - An object implementing ImplicitContextKeyedReturns: A new Context with the value stored
Usage Example:
// Assuming TraceSpan implements ImplicitContextKeyed
TraceSpan span = tracer.spanBuilder("operation").startSpan();
Context contextWithSpan = Context.current().with(span);Makes this context the current context and returns a scope for cleanup.
Scope makeCurrent();Returns: A Scope that must be closed to restore the previous context
Usage Example:
Context newContext = Context.current().with(USER_ID_KEY, "user123");
try (Scope scope = newContext.makeCurrent()) {
// Within this scope, Context.current() returns newContext
performOperation(); // This operation sees the new context
// Nested contexts work too
Context nestedContext = Context.current().with(OPERATION_KEY, "nested");
try (Scope nestedScope = nestedContext.makeCurrent()) {
performNestedOperation();
} // Nested context restored
} // Original context restored automaticallyImportant Notes:
Multiple context modifications can be chained together:
// Chain multiple with() calls
Context enrichedContext = Context.current()
.with(USER_ID_KEY, "user123")
.with(REQUEST_ID_KEY, "req-456")
.with(TENANT_ID_KEY, "tenant789");
try (Scope scope = enrichedContext.makeCurrent()) {
// All three values are available
String userId = Context.current().get(USER_ID_KEY);
String requestId = Context.current().get(REQUEST_ID_KEY);
String tenantId = Context.current().get(TENANT_ID_KEY);
}Context operations are generally safe and do not throw exceptions:
get() returns null for missing keyswith() always returns a valid contextmakeCurrent() always returns a valid scope// Safe to call with any key
String value = Context.current().get(UNKNOWN_KEY); // Returns null
// Safe to store null values
Context ctxWithNull = Context.current().with(SOME_KEY, null);Install with Tessl CLI
npx tessl i tessl/maven-io-opentelemetry--opentelemetry-context