Skip to content

Introduce ContextThreadFactory#529

Open
philsttr wants to merge 1 commit into
micrometer-metrics:mainfrom
philsttr:context_thread_factory
Open

Introduce ContextThreadFactory#529
philsttr wants to merge 1 commit into
micrometer-metrics:mainfrom
philsttr:context_thread_factory

Conversation

@philsttr

@philsttr philsttr commented Apr 21, 2026

Copy link
Copy Markdown

Introduce ContextThreadFactory to propagate context to new Threads created by a delegate ThreadFactory.

The new ContextThreadFactory class was loosely modeled after the existing ContextExecutorService class. They serve essentially the same purpose, but ContextThreadFactory wraps a ThreadFactory instead of an ExecutorService.

See this related comment

Example usage with Java 25's Structured Concurrency preview:

public class RobotAssemblyService {

    // Wrap a ThreadFactory with a ContextThreadFactory that propagates context
    private final ThreadFactory threadFactory = ContextThreadFactory.wrap(
            Thread.ofVirtual().name("robot-assembly-", 0).factory(),
            ContextSnapshotFactory.builder().build());

    public Robot assemble() throws InterruptedException {
        try (var scope = StructuredTaskScope.open(
                awaitAllSuccessfulOrThrow(),
                configuration -> configuration
                        .withName("robot-assemble")
                        .withTimeout(Duration.ofSeconds(2))
                        // use the ContextThreadFactory
                        .withThreadFactory(threadFactory))) {

            Subtask<Arm> armTask = scope.fork(this::assembleArm);
            Subtask<Leg> legTask = scope.fork(this::assembleLeg);

            scope.join();

            Arm arm = armTask.get();
            Leg leg = legTask.get();
            return new Robot(arm, leg);
        } catch (FailedException e) {
            throw new RobotAssemblyException(e.getCause());
        } catch (TimeoutException e) {
            throw new RobotAssemblyException(e);
        }
    }

    // ...
}

Introduce ContextThreadFactory to propagate context to new Threads created by a delegate ThreadFactory.

The new ContextThreadFactory class was modeled after the existing ContextExecutorService class.
They serve essentially the same purpose, but ContextThreadFactory wraps a ThreadFactory instead of an ExecutorService.

Signed-off-by: Phil Clay <philsttr@users.noreply.github.com>
@philsttr

Copy link
Copy Markdown
Author

circleci failure on jdk 11 looks unrelated to my change.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant