Backend Development 4 min read

Using Traceable Thread Pools in Spring Cloud to Preserve Trace Context

This article explains why and how to enforce the use of trace‑aware thread pools in Spring Cloud, presenting three approaches—including TraceableExecutorService, Tracer.currentTraceContext().wrap, and TraceCallable/TraceRunnable—to prevent loss of distributed tracing information in multithreaded applications.

Cognitive Technology Team
Cognitive Technology Team
Cognitive Technology Team
Using Traceable Thread Pools in Spring Cloud to Preserve Trace Context

To avoid loss of trace information when executing tasks in a multithreaded environment, Spring Cloud applications should use thread pools that carry the tracing context.

1. Use TraceableExecutorService to proxy the original thread pool . You can create an instance via the constructor:

public TraceableExecutorService(BeanFactory beanFactory, final ExecutorService delegate) {
    this(beanFactory, delegate, null);
}

public TraceableExecutorService(BeanFactory beanFactory, final ExecutorService delegate, String spanName) {
    this.delegate = delegate;
    this.beanFactory = beanFactory;
    this.spanName = spanName;
}

Or use the static factory methods which cache the wrapped executor:

public static TraceableExecutorService wrap(BeanFactory beanFactory, ExecutorService delegate, String beanName) {
    return CACHE.computeIfAbsent(delegate, e -> new TraceableExecutorService(beanFactory, delegate, beanName));
}

public static TraceableExecutorService wrap(BeanFactory beanFactory, ExecutorService delegate) {
    return CACHE.computeIfAbsent(delegate, e -> new TraceableExecutorService(beanFactory, delegate, null));
}

2. Use org.springframework.cloud.sleuth.Tracer#currentTraceContext().wrap to proxy the original thread pool . Example configuration:

package com.example.demo;

import com.google.common.util.concurrent.ThreadFactoryBuilder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.sleuth.Tracer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.concurrent.*;

/**
 * @author 认知科技技术团队
 */
@Configuration
@Slf4j
public class ThreadPoolConfig {

    @Autowired
    private Tracer tracer;

    @Bean
    public ExecutorService demoExecutorService() {
        ThreadFactory threadFactory = new ThreadFactoryBuilder()
                .setNameFormat("demo-pool-%d")
                .setUncaughtExceptionHandler((t, e) -> {
                    log.error("UncaughtExceptionHandler {}", t, e);
                }).build();

        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(1,
                1,
                1,
                TimeUnit.HOURS,
                new ArrayBlockingQueue<>(100),
                threadFactory,
                new ThreadPoolExecutor.CallerRunsPolicy() {
                    @Override
                    public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
                        log.error("rejectedExecution", e);
                        super.rejectedExecution(r, e);
                    }
                });
        return tracer.currentTraceContext().wrap(threadPoolExecutor);
    }
}

3. Use the provided wrappers TraceCallable and TraceRunnable to execute tasks while preserving the trace:

org.springframework.cloud.sleuth.instrument.async.TraceCallable
org.springframework.cloud.sleuth.instrument.async.TraceRunnable

Summary : In a Spring Cloud environment, forcibly using thread pools that carry tracing information—such as TraceableExecutorService, Tracer.currentTraceContext().wrap, or the TraceCallable/TraceRunnable wrappers—prevents loss of distributed trace data across asynchronous executions.

JavaBackend Developmentthread poolSpring CloudSleuthTrace Context
Cognitive Technology Team
Written by

Cognitive Technology Team

Cognitive Technology Team regularly delivers the latest IT news, original content, programming tutorials and experience sharing, with daily perks awaiting you.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.