使用Guava的ListeningExecutorService装饰线程池

import com.google.common.collect.MapMaker;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @description:
    <dependency>
        <groupId>com.google.guava</groupId>
        <artifactId>guava</artifactId>
        <version>19.0</version>
    </dependency>
 * @author: 码上得天下
 * @create: 2019-12-19 14:39
 **/
public class CustomizableThreadPool {
    //存放线程池map
    private static ConcurrentMap<String, ListeningExecutorService> executorServiceMap = new MapMaker().concurrencyLevel(32).makeMap();
    private static byte[] lock = new byte[0];
    public static <T>ListeningExecutorService getExecutorService(String poolName){
        ListeningExecutorService executorService=executorServiceMap.get(poolName);
        if (null==executorService){
            //此处未设置拒绝策略,业务代码中使用会配置3秒超时,也未设置统一异常处理,业务代码处理
            //第一次调用时候可能会有多线程问题
            synchronized (lock) {
                executorService = MoreExecutors.
                        listeningDecorator
                                (new ThreadPoolExecutor(8,16,30, TimeUnit.SECONDS
                                        ,new LinkedBlockingQueue<Runnable>(),
                                        new CustomizableThreadFactory(poolName)));
                executorServiceMap.put(poolName, executorService);
            }
        }

        return executorService;
    }

    //装饰线程池名字
    public static class CustomizableThreadFactory implements ThreadFactory {

        private final String namePrefix;
        private final AtomicInteger threadNumber = new AtomicInteger(1);

        public CustomizableThreadFactory(String poolName) {
            namePrefix = poolName + "-";
        }
        @Override
        public Thread newThread(Runnable runable) {
            return new Thread(runable, namePrefix + threadNumber.getAndIncrement());
        }
    }


}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值