Backend Development 4 min read

Enforcing Traceable Thread Pools in Spring Cloud to Preserve Trace Context

This article explains how to prevent loss of tracing information in Spring Cloud by using traceable thread pools, detailing three approaches: wrapping an ExecutorService with TraceableExecutorService, using Tracer.currentTraceContext().wrap, and employing TraceCallable/TraceRunnable for context propagation.

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

To avoid loss of trace information in multithreaded environments, Spring Cloud provides traceable thread pools that automatically propagate the tracing context.

There are several ways to use traceable thread pools:

1. Use TraceableExecutorService to wrap an existing ExecutorService . It can be instantiated via a constructor or static factory methods, which also cache the wrapped pool.

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;
}
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 Tracer.currentTraceContext().wrap to wrap a ThreadPoolExecutor directly, as shown in the 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 TraceCallable and TraceRunnable classes to submit tasks that preserve the trace context.

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

In summary, enforcing the use of traceable thread pools in Spring Cloud ensures that trace information is not lost across asynchronous executions.

Backend Developmentthread poolSpring CloudtracingSleuth
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.