open-telemetry / open-telemetry/opentelemetry-java

Context.Scope is great for public APIs, but may cause extra allocations for low-level things

Open
#2,739 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Feature Request release:after-ga
Dominant language
Java
Stars
2.5k
Forks
1k
Avg merge
3d 17h
Merged PRs (30d)
58

Description

I think exposing Scope as the only way to attach a Context is great, but I think it would be good if the ContextStorage exposes a low-level APIs attach/detach or something similar that do not require a new object all the time.

Example:

  /**
   * Returns a {@link Runnable} that makes this the {@linkplain Context#current() current context}
   * and then invokes the input {@link Runnable}.
   */
  default Runnable wrap(Runnable runnable) {
    return () -> {
      try (Scope ignored = makeCurrent()) {
        runnable.run();
      }
    };
  }

This code needs 2 allocations (one for the return Runnable, and will do an allocation when makeCurrent is called), but we can in this case re-write this like:

  /**
   * Returns a {@link Runnable} that makes this the {@linkplain Context#current() current context}
   * and then invokes the input {@link Runnable}.
   */
  default Runnable wrap(Runnable runnable) {
    return () -> {
      Context toDetach = storage.attach(this);
      try () {
        runnable.run();
      } finally {
        storage.detach(toDetach);
      }
    };
  }

The attach/detach APIs are for example, probably we need better APIs for that and we need to think about them.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reviewing the Context.Scope and ContextStorage APIs referenced in the issue, along with the wrap(Runnable) example. Clarify the proposed low-level attach/detach semantics and API shape before implementation. Done means an agreed design that reduces unnecessary Scope allocations without changing context restoration behavior.

Written by the indexing model from the issue text.

Assessment

Tech stack
java
Domain
api, backend-api-design
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.