线程池,CompletableFuture学习

   最近在做gRPC对服务端的压测,从开发身上学习到了高级用法,记录一下:

   简单说,就是长连接不释放导致TCP连接数耗尽,期望通过http2解决这个问题,也就是说,其实是用gRPC来重写了消息服务,因此需要高并发(并不是)及异步编程。

   开发review了我的代码以后,重写成这样了,记录在这里学习下。

   

CompletableFuture<?>[] completableFutures = new CompletableFuture[num];
ExecutorService executorService = Executors.newFixedThreadPool(200);
Stopwatch mainWatch = Stopwatch.createStarted();
for (int i = 0; i < num; i++) {
completableFutures[i] = CompletableFuture.runAsync( () -> xxxxService.sendMessage("xielu_test")
, executorService);
}
CompletableFuture.allOf(completableFutures).join();

   再来一版好了,双重异步!

   

public ListenableFuture<ReportResponse> sendMessage(String message) {
ListeningExecutorService service = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(10));
try {
ListenableFuture<ReportResponse> responseFuture = messageReportStub.report(ReportRequest.newBuilder().setMessage(message).build());
return responseFuture;
} catch (final StatusRuntimeException e) {
return null;
}
}
-------------------------我是类的分割线-------------------------------------------------------------------------------------------------------

  

CompletableFuture completableFuture = new CompletableFuture();
ListenableFuture<ReportResponse>[] completableFutures = new ListenableFuture[num];
ListeningExecutorService executorService = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(100));
Stopwatch mainWatch = Stopwatch.createStarted();
for (int i = 0; i < num; i++) {
completableFutures[i] = client.sendMessage("xielu_test");
}
Futures.addCallback(Futures.allAsList(completableFutures), new FutureCallback<List<ReportResponse>>() {
@Override
public void onSuccess(List<ReportResponse> reportResponses) {
completableFuture.complete(reportResponses);
}

@Override
public void onFailure(Throwable throwable) {
completableFuture.completeExceptionally(throwable);
}
}, executorService);
completableFuture.get();
long elapsed = mainWatch.elapsed(TimeUnit.MILLISECONDS);
String message = String.format("seed: %d, totalTime: %dms, tps: %d", num, elapsed, Math.round(num / (double) elapsed * 1000));

转载于:https://www.cnblogs.com/spillage/p/11422971.html

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值