【记录】并发辅助类ConcurrentHelper

@Slf4j
public class ConcurrentHelper {

    private final ThreadPoolExecutor threadPoolExecutor;
    /**
     * 最长等待时间,单位小时,默认2小时
     */
    private long timeout = 1000 * 60 * 60 * 2;

    public ConcurrentHelper() {
        this.threadPoolExecutor = DefaultConcurrentPool.defaultConcurrentSyncExecutor();
    }

    /**
     * 默认构造器
     *
     * @param threadPoolExecutor 线程池
     */
    public ConcurrentHelper(ThreadPoolExecutor threadPoolExecutor) {
        this.threadPoolExecutor = threadPoolExecutor;
    }

    /**
     * 可以自定义超时时间
     *
     * @param threadPoolExecutor 线程池
     * @param timeout            超时时间,单位毫秒
     */
    public ConcurrentHelper(ThreadPoolExecutor threadPoolExecutor, long timeout) {
        this.threadPoolExecutor = threadPoolExecutor;
        this.timeout = timeout;
    }

    /**
     * 并发处理集合数据,当多个pod时,能提升执行速度,限制并发数,最大等待队列
     * 并发之后,会等待当前list执行完成之后,在进行下一轮并发
     *
     * @param list    待处理列表数据
     * @param handler 处理器
     * @param <T>     处理对象
     */
    synchronized public <T> void concurrentProcessor(List<T> list, Consumer<T> handler) {
        if (list == null || list.isEmpty()) {
            return;
        }
        // 防止被决绝导致无法退出
        int size = threadPoolExecutor.getQueue().remainingCapacity() + threadPoolExecutor.getMaximumPoolSize();
        CountDownLatch countDownLatch = new CountDownLatch(Math.min(size, list.size()));
        list.forEach(t -> threadPoolExecutor.execute(() -> {
                    try {
                        handler.accept(t);
                    } finally {
                        // 无论抛出任何异常,都应该保证线程阻塞数量降低,结束当前线程
                        countDownLatch.countDown();
                    }
                }
        ));
        // 阻塞等待线程池任务执行完
        try {
            // 最长允许执行2小时,解决一直阻塞的问题,如果list执行需要超过2H的需要注意是否拆分更小的list
            boolean await = countDownLatch.await(timeout, TimeUnit.MILLISECONDS);
            if (await) {
                log.info("[ConcurrentHelper.concurrentProcessor] 并发处理器执行成功,size:{}", list.size());
            } else {
                log.warn("[ConcurrentHelper.concurrentProcessor] 并发处理器await失败,size:{}", JsonUtil.toJson(list));
            }
        } catch (InterruptedException e) {
            log.error("[ConcurrentHelper.concurrentProcessor] 并发处理器await异常,e:", e);
        }
    }
}
public class DefaultConcurrentPool {
    public static ThreadPoolExecutor defaultConcurrentSyncExecutor() {
        ThreadFactory threadFactory = new ThreadFactoryBuilder()
                .setNameFormat("Default-concurrent-%d").build();

        return new ThreadPoolExecutor(4,
                8,
                10L, TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(512), threadFactory, new ThreadPoolExecutor.DiscardPolicy());
    }
}

推广:全民简历 - 专业简历制作服务平台【官网】

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

十二月的雪7

你的鼓励将是我创作最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值