java - 在 CompletableFuture 类中使用 join 方法与 get 方法
问题描述
我想实现一个功能,将大文件分解成块并且可以并行进行处理。
我使用 CompletableFuture 并行运行任务。不幸的是,除非我使用加入,否则它不起作用。我很惊讶这种情况正在发生,因为根据文档,get 也是类中返回结果的阻塞方法。有人可以帮我弄清楚我做错了什么。
//cf.join(); if i uncommnet this everything works
如果我在方法 processChunk 中取消注释上述行,一切正常。我的价值观被打印出来了。但是,如果我将其删除,则不会发生任何事情。我得到的只是期货已完成但内容未打印的通知。
这是我的输出
i cmpleteddone
i cmpleteddone
i cmpleteddone
i cmpleteddone
i cmpleteddone
我的文本文件是一个非常小的文件(现在)
1212451,London,25000,Blocked
1212452,London,215000,Open
1212453,London,125000,CreditBlocked
1212454,London,251000,DebitBlocked
1212455,London,2500,Open
1212456,London,4000,Closed
1212457,London,25100,Dormant
1212458,London,25010,Open
1212459,London,27000,Open
12124510,London,225000,Open
12124511,London,325000,Open
12124512,London,425000,Open
12124513,London,265000,Open
12124514,London,2577000,Open
12124515,London,2504400,Open
package com.org.java_trial.thread.executors;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ProcessReallyBigFile {
private static final ExecutorService ex = Executors.newFixedThreadPool(5);
private static CompletableFuture<String> processChunk(List<String> lines) {
CompletableFuture<String> cf = CompletableFuture.supplyAsync(() -> {
//just for purposes of testing, will be replaced with major function later
lines.stream().forEach(System.out::println);
return "done";
}, ex);
//cf.join(); if i uncommnet this everything works
return cf;
}
private static void readInChunks(String filepath, Integer chunksize) {
List<CompletableFuture<String>> completable = new ArrayList<>();
try (BufferedReader reader = Files.newBufferedReader(Paths.get(filepath))) {
String line = null;
List<String> collection = new ArrayList<String>();
int count = 0;
while ((line = reader.readLine()) != null) {
if (count % chunksize == chunksize - 1) {
collection.add(line);
completable.add(processChunk(collection));
collection.clear();
} else {
collection.add(line);
}
count++;
}
// any leftovers
if (collection.size() > 0)
completable.add(processChunk(collection));
} catch (IOException e) {
e.printStackTrace();
}
for (CompletableFuture c : completable) {
c.join();
if (c.isDone() || c.isCompletedExceptionally()) {
try {
System.out.println("i cmpleted" + c.get());
} catch (InterruptedException | ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
ex.shutdown();
}
public static void main(String[] args) {
String filepath = "C:\\somak\\eclipse-workspace\\java_thingies\\java_trial\\account_1.csv";
readInChunks(filepath, 3);
}
}
解决方案
原因是这样的:
collection.clear();
您的控件将返回到调用方法,.join()
并且您的任务所引用的集合被清除。luck you ain't getting an exception thrown for concurrent access
. 对共享资源的并发访问应始终保持同步。我宁愿这样做:
synchronized(collection) {
collection.clear();
}
和
synchronized(collection) {
lines.stream().forEach(System.out::println);
}
这将确保访问collection
对象时的线程安全,因为线程需要collection
在对其执行任何更新之前将监视器保持在实例上。
另外,正如@Holger 所指出的,这样做:
synchronized(collection) {
collection.add(line);
}
推荐阅读
- r - 设置绘图的添加平均线的 y 限制
- sql-server - TSQL - 查找表中的记录,其中一列中有多个记录,并且在另一列中至少出现一个特定值
- c++ - 如何在没有动态内存分配(堆)的情况下为可变大小数组(向量)定义安全容器或视图?
- python - 将二进制格式的 word2vec 向量导入 spacy
- php - 通过字符对齐问题写入文本字符
- angular - 如何将数据传递给组件到另一个组件
- cordova-plugins - 在 MicroBlink 框架中找不到 Armv7 和 Arm64 的符号
- python - 运行示例 python-telegram-bot 代码时发生错误
- javascript - 从日期对象中仅获取小时和分钟
- apache-spark - 调用其他笔记本时Databricks笔记本超时错误:com.databricks.WorkflowException:java.net.SocketTimeoutException:读取超时