gpt4 book ai didi

java - 在 Java 8 中解析/处理 List>> 的最佳方法

转载 作者:行者123 更新时间:2023-12-04 10:28:20 26 4
gpt4 key购买 nike

代码:
Spring bean 片段:

@Component
class myService {

private CSVFileProcessor csvFileProcessor;

public myService(CSVFileProcessor csvFileProcessor) {

this.csvFileProcessor=csvFileProcessor;

}

/* input: List of promises/futures obtained by reading
* csv files from S3 bucket
*
* output: List of promises of list of parsed csv
* documents converted to POJO's of type Document
*
*
*/
@Async
public List<CompletableFuture<List<Document>>> createDocumentObjects(
List<CompletableFuture<ResponseBytes<GetObjectResponse>>> documentsFuture) {

return documentsFuture.stream().map(myDocument-> myDocument.thenCompose(document-> CompletableFuture.supplyAsync(
() -> csvFileProcessor.parseObjects(document)))).collect(Collectors.toList());

}

所以在服务层我注入(inject)了上面的bean并尝试做一些类似的事情:
List<CompletableFuture<List<Document>>> listOfPromises= injectedBean.createDocumentObjects(input);

//The below code throws NPE(Null pointer exception)
List<List<Document>> myDocuments =listOfPromises.stream().map(CompletableFuture::join).collect(Collectors.toList());
listOfPromises似乎为空。我检查了 csvFileProcessor 的日志类和输入正在按预期进行处理。尝试向 future 的调用添加异常和处理 block ,但在尝试解决 promise 时,除了同一个 NPE 之外,这些地方仍然没有抛出异常。

我确定我遗漏了一些微不足道的东西,任何正确方向的指导都会非常有帮助。

最佳答案

根据 @Async documentation :

In terms of target method signatures, any parameter types are supported. However, the return type is constrained to either void or Future. In the latter case, you may declare the more specific ListenableFuture or CompletableFuture types which allow for richer interaction with the asynchronous task and for immediate composition with further processing steps.



您的方法都不返回这些,因此 Spring 不知道如何处理它。不幸的是,它没有给出错误,而是接受调用,将方法执行推迟到单独的线程并立即返回 null .

然而,您似乎并不真正需要 @Async在这里,由于您的方法正在处理异步执行本身(通过组合和 supplyAsync() ),因此您可能只需删除注释即可解决问题。

关于java - 在 Java 8 中解析/处理 List<CompletableFuture<List<Object>>> 的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60534658/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com