Java异步并发和线程池


参考1:
https://wenku.baidu.com/view/a9cdf1c09889680203d8ce2f0066f5335a81672a.html
参考2:
https://www.cnblogs.com/weilx/p/16329743.html

1.一条简单粗暴的路:

使用java的parallelStream可以轻松实现并发,不需要考虑多线程的问题,但有一些要注意的地方

a.使用 parallelStream可能存在的bug

在parallelStream的外部创建List 或者Map,然后在parallelStream内部对List或者Map进行塞值得时候,可能会因为抢占资源,导致部分元素丢失。

b. 如何正确使用 parallelStream

一个简单的方法是使用java的收集器Collectors配合parallelStream的collect函数。

2.另一条路

另一条路是再Spring中自定义线程池,然后配合并发调用
1.定义线程池


import com.dianping.cat.Cat;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.ymm.framework.dgc.thread.executor.EnhancedThreadPoolExecutor;  //可以使用java原生线程池
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Configuration
@EnableAsync
public class Thread {

    @Bean(name = "cargoServiceExecutor")
    public EnhancedThreadPoolExecutor cargoServiceExecutor() {
        EnhancedThreadPoolExecutor executor =
                new EnhancedThreadPoolExecutor((3 * Runtime.getRuntime().availableProcessors()) + 1, 60, 120L, TimeUnit.SECONDS,
                        new LinkedBlockingQueue(1024));
        executor.setRejectedExecutionHandler(new CustomKafkaDiscardPolity());
        executor.setThreadFactory(new ThreadFactoryBuilder().setNameFormat("cargoService-thread-%d").build());
        return executor;
    }
    static class CustomKafkaDiscardPolity extends ThreadPoolExecutor.DiscardPolicy {
        @Override
        public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
            Cat.logEvent("ThreadPoolDisCard", "cargoService");
        }
    }
}

2.stream配合异步CompletableFuture,使用线程池

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

List<CargoDto> cargoDtoList = Lists.newArrayList();
List<CompletableFuture<List<CargoDto>>> routeFeatureDTOResFutureList = new ArrayList<>();
Lists.partition(cargoIdList, realtimeCargoLion.getQueryCargoBatch()).stream().forEach(list -> {
                CompletableFuture<List<CargoDto>> routeFeatureDTOResFuture = CompletableFuture.supplyAsync(() -> rpcService.queryByIds(list),cargoServiceExecutor);
                routeFeatureDTOResFutureList.add(routeFeatureDTOResFuture);
            });

            routeFeatureDTOResFutureList.forEach(future -> {
                try {
                    List<CargoDto> routeFeatureDTOResList = future.get(realtimeCargoLion.getQueryCargoBatchTimeout(), TimeUnit.MILLISECONDS);
                    cargoDtoList.addAll(routeFeatureDTOResList);
                } catch (Exception e) {

                }
            });
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值