java parrallel for,Java 8 parallel forEach进度指示

java parrallel for,Java 8 parallel forEach进度指示ForperformancereasonIwouldliketouseaforEachloopofaparallelLambdastreaminordertoprocessaninstanceofaCollectioninJava.AsthisrunsinabackgroundServiceIwouldliketouse…

大家好,又见面了,我是你们的朋友全栈君。

java parrallel for,Java 8 parallel forEach进度指示

For performance reason I would like to use a forEach loop of a parallel Lambda stream in order to process an instance of a Collection in Java. As this runs in a background Service I would like to use the updateProgress(double,double) method in order to inform the user about the current progress.

In order to indicate the current progress I need a certain progress indicator in form of a Integer counter. However, this is not possible as I can only access final variables within the Lambda expression.

Code example see below, Collection is only a place holder for any possible instance of a Collection:

int progress = 0;

Collection.parallelStream().forEach(signer -> {

progress++;

updateProgress(progress, Collection.size());

});

I’m aware that I can solve this problem by using a simple for-loop. However, for performance reason it would nice to solve it in this way.

Does anybody know a more or less neat solution to this?

解决方案

As proposed by markspace, using an AtomicInteger is a good solution:

AtomicInteger progress = new AtomicInteger();

Collection.parallelStream().forEach(signer -> {

progress.incrementAndGet();

// do some other useful work

});

I would not use the runLater() variant as your goal is a high performance, and if many parallel threads will generte JavaFX ‘runLater’ tasks, you will again create a bottleneck…

For the same reason I would NOT call an update to the ProgressBar each time, but use a seaparte JavaFX Timeline to update the progress bar in regular intervals independently from the processing threads.

Here is a full code comparing sequential and parallel processing with ProgressBar. If you remove the sleep(1) and set the number of items to 10 million it will still work concurrently and efficiently…

public class ParallelProgress extends Application {

static class ParallelProgressBar extends ProgressBar {

AtomicInteger myDoneCount = new AtomicInteger();

int myTotalCount;

Timeline myWhatcher = new Timeline(new KeyFrame(Duration.millis(10), e -> update()));

public void update() {

setProgress(1.0*myDoneCount.get()/myTotalCount);

if (myDoneCount.get() >= myTotalCount) {

myWhatcher.stop();

myTotalCount = 0;

}

}

public boolean isRunning() { return myTotalCount > 0; }

public void start(int totalCount) {

myDoneCount.set(0);

myTotalCount = totalCount;

setProgress(0.0);

myWhatcher.setCycleCount(Timeline.INDEFINITE);

myWhatcher.play();

}

public void add(int n) {

myDoneCount.addAndGet(n);

}

}

HBox testParallel(HBox box) {

ArrayList myTexts = new ArrayList();

for (int i = 1; i < 10000; i++) {

myTexts.add(“At “+System.nanoTime()+” ns”);

}

Button runp = new Button(“parallel”);

Button runs = new Button(“sequential”);

ParallelProgressBar progress = new ParallelProgressBar();

Label result = new Label(“-“);

runp.setOnAction(e -> {

if (progress.isRunning()) return;

result.setText(“…”);

progress.start(myTexts.size());

new Thread() {

public void run() {

long ms = System.currentTimeMillis();

myTexts.parallelStream().forEach(text -> {

progress.add(1);

try { Thread.sleep(1);} catch (Exception e1) { }

});

Platform.runLater(() -> result.setText(“”+(System.currentTimeMillis()-ms)+” ms”));

}

}.start();

});

runs.setOnAction(e -> {

if (progress.isRunning()) return;

result.setText(“…”);

progress.start(myTexts.size());

new Thread() {

public void run() {

final long ms = System.currentTimeMillis();

myTexts.forEach(text -> {

progress.add(1);

try { Thread.sleep(1);} catch (Exception e1) { }

});

Platform.runLater(() -> result.setText(“”+(System.currentTimeMillis()-ms)+” ms”));

}

}.start();

});

box.getChildren().addAll(runp, runs, progress, result);

return box;

}

@Override

public void start(Stage primaryStage) throws Exception {

primaryStage.setTitle(“ProgressBar’s”);

HBox box = new HBox();

Scene scene = new Scene(box,400,80,Color.WHITE);

primaryStage.setScene(scene);

testParallel(box);

primaryStage.show();

}

public static void main(String[] args) { launch(args); }

}

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/161787.html原文链接:https://javaforall.net

赞 (0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • 高斯同余理论_高斯模糊算法

    高斯同余理论_高斯模糊算法针对鲸鱼优化算法在处理高维问题时存在收敛速度慢、容易陷入局部最优和收敛精度低等问题,提出一种基于对数惯性权重和高斯差分变异的鲸群优化算法。通过高斯差分变异对鲸鱼位置更新方程进行变异,增加了种群多样性,提高了鲸群算法的全局搜索能力,防止早熟现象发生;将对数惯性权重引入搜寻猎物阶段,平衡全局搜索和局部开发能力,提高了算法寻优精度。通过测试函数优化实验对算法进行测试,实验结果表明,改进算法具有更高的寻优精度和更快的收敛速度。

    2022年10月5日
  • origin画图怎么拟合曲线_origin拟合平滑曲线

    origin画图怎么拟合曲线_origin拟合平滑曲线需要用到matlab的拟合曲线中的smoothingspline功能,同时origin画的图又比较好看且可以后续做多条切线,因此记录下matlab与origin联合使用的方法,并加上用origin的tangent插件做曲线多条切线的方法。

    2022年9月21日
  • icem二维非结构网格划分_ICEM蜗壳非结构网格划分[通俗易懂]

    icem二维非结构网格划分_ICEM蜗壳非结构网格划分[通俗易懂]ICEM-蜗壳网格划分导入模型你需要在ICEM中导入你的模型,一般用的模型格式为STP、IGS、X_T等通用第三方格式。同时如果你有提前画好的网格你也可以导入进来。PRAT建立创建好各部分的Part,并创建body,与此同时修复模型,对于简单的模型只需要做一个修复模型的命令就行,但是对于一些复杂的模型再导入到ICEM中很多部位都是需要做修复的,这时候就需要对这一部分破损的模型进行修复。…

    2022年5月22日
  • 关于使用preparestatement来实现模糊查询

    关于使用preparestatement来实现模糊查询关于使用prparestatement来实现模糊查询

    2022年6月4日
  • jenkins教程_1 简介「建议收藏」

    jenkins教程_1 简介「建议收藏」文章内容https://gitee.com/fakerlove/jenkins文章目录1.简介1.1介绍1.2环境准备1.2.1安装jenkins1)离线安装2)docker安装3)访问jenkins1.2.2安装gitlab一、安装及配置1.gitlab镜像拉取2.运行gitlab镜像3.配置4.创建一个项目二、用户使用1.下载git.exe2.登录gitlab网页3.设置ssh4.从gitlab克隆代码5.提交代码到gitlab1.2.3gitlab占用内存太多问题1.简.

    2022年5月15日
  • html手机端下拉菜单代码,jQuery手机移动端下拉列表选择代码「建议收藏」

    js代码$(function(){$(‘.retriedta’).click(function(){var$t=$(this);if($t.hasClass(‘up’)){$(“.retriedta”).removeClass(‘up’);$(‘.downlist’).hide();$(‘.mask’).hide();}else{$(“.retriedta”).removeClass…

    2022年4月15日

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号