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)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • 锁定文件失败 未能启动虚拟机_win10无法分析无人应答文件

    锁定文件失败 未能启动虚拟机_win10无法分析无人应答文件首先看一下出现的错误:出现这个错误我也是纠结了好半天,试了网上的方法结果还是没有效果,比如下面的这个方法也不行,不知道是不是我机器的问题:后来误打误撞地把问题解决了,在创建虚拟机的最后一步将勾选的“创建后开启此虚拟机(P)”去的,即不勾选,创建完后再手动启动虚拟机,就可以了,如下图所示:…

    2025年11月14日
    6
  • matlab自带的插值函数interp1的几种插值方法

    matlab自带的插值函数interp1的几种插值方法插值法    插值法又称“内插法”,是利用函数f(x)在某区间中已知的若干点的函数值,作出适当的特定函数,在区间的其他点上用这特定函数的值作为函数f(x)的近似值,这种方法称为插值法。如果这特定函数是多项式,就称它为插值多项式。线性插值法    线性插值法是指使用连接两个已知量的直线来确定在这两个已知量之间的一个未知量的值的方法。    假设我们已知坐标(x0,y0)与…

    2022年6月13日
    39
  • ubuntu安装pip3_ubuntu查看python包

    ubuntu安装pip3_ubuntu查看python包ubuntu安装pip一、pip是什么二、pip命令行安装三、源文件安装四、出现的报错我的环境:ubuntu18.04一、pip是什么简单来时:pip是Python中的标准库管理器。它允许你安装和管理不属于Python标准库的其它软件包。二、pip命令行安装安装:sudoaptinstallpython3-pip更新:pip3install–upgradepip验证:pip-V三、源文件安装如果上面的方法失效后,可以使用这种编译源码的方法:1、安装set

    2025年8月20日
    12
  • 2016年四川省TI杯电子设计竞赛B题

    2016年四川省TI杯电子设计竞赛B题B题:自动循迹小车1.任务设计制作一个自动循迹小车。小车采用一片TI公司LDC1314或LDC1000电感数字转换器作为循迹传感器,在规定的平面跑道自动按顺时针方向循迹前进。跑道的标识为一根直径0.6~0.9mm的细铁丝,按照图1的示意尺寸,用透明胶带将其贴在跑道上。图中所有圆弧的半径均为为20cm±2cm。图1跑道示意图2.要求(1)在图1小车所在的直线区任意指定一

    2022年6月7日
    31
  • 主流自动化运维工具支持的功能(运维自动化工具排行)

    主流的自动化运维工具有3种:Puppet、Saltstack和Ansible,用的最多的还是Ansible。Puppet:官网:www.puppetlabs.com,基于rubby开发,C/S架构,支持多平台,可管理配置文件、用户、cron任务、软件包、系统服务等。分为社区版(免费)和企业版(收费),企业版支持图形化配置。Saltstack:官网:https://saltsta…

    2022年4月13日
    49
  • CListCtrl详细使用方法

    CListCtrl详细使用方法以下未经说明,listctrl默认view风格为report相关类及处理函数MFC:CListCtrl类SDK:以“ListView_”开头的一些宏。如ListView_InsertColumnCListCtrl风格LVS_ICON:为每个item显示大图标LVS_SMALLICON:为每个item显示小图标LVS_LIST:显示一列带有小图标的i

    2022年6月23日
    27

发表回复

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

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