ThreadFactoryBuilder,它更好!

2022/4/11 23:17:10

本文主要是介绍ThreadFactoryBuilder,它更好!,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

我们程序的链路追踪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 ThreadFactoryBuilder().setNameFormat("PaymentService_pool_%d").build());

 

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呢?

欢迎交流!



这篇关于ThreadFactoryBuilder,它更好!的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程