我们程序的链路追踪id(trace_id)通常通过线程名来实现。

相较于juc.ThreadFactory来说,hutool、guava均提供了ThreadFactoryBuilder,更方便我们使用。

 

JUC下面原生ThreadFactory类

// import java.util.concurrent.ThreadFactory;

private static ExecutorService paymentPool = Executors.newSingleThreadExecutor(new ThreadFactory() {
@Override
public Thread newThread(@NotNull Runnable r) {
return new Thread(r, "Alipay-Msg-Thread");
}
});

这种方式创建的线程名都是相同的。不太契合我们记日志的需求。

2022-03-23 12:20:14,019 INFO [Alipay-Msg-Thread] TestMain (TestMain:67) - ddd

 

hutool里的ThreadFactoryBuilder

// import cn.hutool.core.thread.ThreadFactoryBuilder

private static ScheduledExecutorService scheduledThreadPoolExecutor = Executors.newScheduledThreadPool(5,
ThreadFactoryBuilder.create().setNamePrefix(PaymentServiceImpl.class.getSimpleName().concat("_")).build());

log效果:

2022-03-23 12:20:14,019 INFO [PaymentServiceImpl_1] TestMain (TestMain:70) - sched2
2022-03-23 12:20:14,019 INFO [PaymentServiceImpl_0] TestMain (TestMain:68) - sched

 

google guava.jar里的ThreadFactoryBuilder

 

// import com.google.common.util.concurrent.ThreadFactoryBuilder

private static ExecutorService paymentPool = Executors.newSingleThreadExecutor(
new

 

log效果:

2022-03-23 12:20:14,019 INFO [PaymentService_pool_1] TestMain (TestMain:67) - ddd
2022-03-23 12:20:14,019 INFO [PaymentService_pool_2] TestMain (TestMain:67) - ddd

 

比较

hutool的ThreadFactoryBuilder提供的api是设置线程名前缀,我们无需关注占位符。

guava的ThreadFactoryBuilder提供的api是format,需考虑占位符。

另外,从建造者模式(Builder Pattern)的角度来说,通常我们在使用时,应先调用实例的create或build方法,这一点,hutool做得稍优秀一些。

相比来说,个人觉得hutool更容易上手使用。

 

你用哪些ThreadFactoryBuilder呢?

欢迎交流!