Java 8:如何将for循环转换为并行运行? [英] Java 8: How can I convert a for loop to run in parallel?

查看:619
本文介绍了Java 8:如何将for循环转换为并行运行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

for (int i=0; i<100000; i++) {
    // REST API request. 
restTemplate.exchange(url, HttpMethod.GET, request, String.class);
}

我有一种情况需要为100k用户请求资源需要70分钟才能完成。我试图尽可能地清理我的代码,我只能将它减少4分钟)。

I have a situation where I have to request a resource for 100k users and it takes 70 minutes to finish. I tried to clean up my code as much as possible and I was able to reduce it only by 4 minutes).

由于每个请求彼此独立,我很乐意并行发送请求(可能是10s,100s甚至1000s的块,每次快速完成) 。我希望我能把时间减少到10分钟或者接近的时间。我如何计算哪个块大小可以快速完成工作?

Since each request is independent of each other, I would love to send requests in parallel (may be in 10s, 100s, or even 1000s of chunks which every finishes quickly). I'm hoping that I can reduce the time to 10 minutes or something close. How do I calculate which chunk size would get the job done quickly?

我找到了以下方法,但我无法确定程序是否处理所有20个时间;或一次5个;或者一次10个。

I have found the following way but I can't tell if the program processes all the 20 at a time; or 5 at a time; or 10 at a time.

IntStream.range(0,20).parallel().forEach(i->{
     ... do something here
});

我知道你的帮助。我对任何建议或评论都持开放态度!

I appericiate your help. I am open to any suggestions or critics!!

更新:我能够使用IntStream并在28分钟内完成任务。但我不确定这是我能做的最好的。

UPDATE: I was able to use IntStream and the task finished in 28 minutes. But I am not sure this is the best I could go for.

推荐答案

我在Java 8中使用了以下代码,它确实工作。我能够将批处理作业从28分钟缩短到3:39分钟。

I used the following code in Java 8 and it did the work. I was able to reduce the batch job to run from 28 minutes to 3:39 minutes.

IntStream.range(0, 100000).parallel().forEach(i->{
     restTemplate.exchange(url, HttpMethod.GET, request, String.class);
}
});

这篇关于Java 8:如何将for循环转换为并行运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆