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); }

}

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

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

【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛

【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...

(0)


相关推荐

  • 加密门禁卡复制

    加密门禁卡复制本文主要是针对一下加密门禁卡解密复制问题。最近发现补一张要50,成本的话白卡2块钱一张,读卡器可以白嫖也可以24多买一个不带壳pn532模块。一.卡类型IC卡是智能卡的总称。普通IC卡,0扇区不可以修改,其他扇区可反复擦写,我们使用的电梯卡、门禁卡等智能卡发卡商所使用的都是M1卡,可以理解为物业发的原卡。UID卡普通复制卡,可以重复擦写所有扇区,主要应用在IC卡复制上,遇到带有防火墙的读卡器就会失效。CUID卡可擦写防屏蔽卡,可以重复擦写所有扇区,UID卡复制无效的情况

  • 软引用SoftReference[通俗易懂]

    软引用SoftReference[通俗易懂]1.对象的引用类….  最近也是通过项目中知道了一些东西,涉及到了对象的引用类,对象的引用类分为多种,强引用(其实就是正常的引用),使用SoftReference实现软引用,WeakReference(弱引用) PhantomRefrence(虚引用)…这三个引用类我只详细的介绍一下SoftReference实现软引用…其他的就一笔带过….强引用:

  • pycharm2019.3.3激活成功教程_pycharm界面

    pycharm2019.3.3激活成功教程_pycharm界面PyCharm是由著名的JetBrains公司所打造的一款功能强大的PythonIDE,它具有一般IDE都具备的功能,并且使用起来非常方便好用。最近需求PyCharm激活码的网友非常多,小编就在这里给大家分享一下PyCharm2019最新可用的激活注册码。激活Pycharm专业版的方法有很多,小编在这里主要给大家分享最有效的两种,一种是使用最新可用的注册激活码,一种是使用激活成功教程补丁的方法,这种方法…

  • 忆贵州三年的教书编程岁月:不弛于空想,不骛于虚声「建议收藏」

    忆贵州三年的教书编程岁月:不弛于空想,不骛于虚声「建议收藏」回首,2016年7月他离开北京回到了家乡贵州,成为了贵州财经大学的一名青年教师。转眼,2019年7月他迎来了人生的第三张通知书,即将辗转第三个城市,开始新的征途。教书三年,讲台前的每一次分享都值得回味,学生的每一句“老师好”,每一个问候和祝福,都留下了深刻的印象。

  • 小程序的图片上传wx.uploadFile及后台PHP接收文件并存储到服务器[通俗易懂]

    小程序的图片上传wx.uploadFile及后台PHP接收文件并存储到服务器[通俗易懂]前台代码wxml:<buttonbindtap=’chooseImg’>选择图片</button>//图片选择<view><imagesrc='{{img_l}}’bindtap=’preview_img’></image></view>//图片预览<buttonbindtap=’up_img’…

  • Isona-0.0.1发布,spring4all社区打造的微服务管理工具,欢迎吐槽与共同完善「建议收藏」

    Isona-0.0.1发布,spring4all社区打造的微服务管理工具,欢迎吐槽与共同完善

发表回复

您的电子邮箱地址不会被公开。

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