1. 程式人生 > 其它 >ThreadFactoryBuilder,它更好!

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