编程语言
首页 > 编程语言> > java – CompletableFuture获得第一个未来的结果,等待其他期货取决于第一个

java – CompletableFuture获得第一个未来的结果,等待其他期货取决于第一个

作者:互联网

我有以下要求.

> CreateDocument
>对于文档创建许多发行说明(releaseNotesFuture)
>对于文档创建许多宗地(parcelsFuture)
>返回1中创建的文档的objectId.

这是我目前的代码:

public CompletableFuture<ObjectId> createDeliveryNoteDocument(String productId, List<String> releaseNotesIds) {
        CompletableFuture<ObjectId> deliveryNoteFuture =
                CompletableFuture
                        .supplyAsync(() -> sequenceServiceFeignClient.getNextValueForSequenceNameNoResponseEntity(DocumentType.DELIVERYNOTE.toString()))
                        .whenComplete((result, error) -> {
                            if (error != null)
                                logger.error("Unable to get next sequence number for DELIVERYNOTE sequence", error);
                        })
                        .thenCompose(seqNumber -> {
                            Set<ObjectAttribute> objectAttributes = new HashSet<>();
                            objectAttributes.add(new ObjectAttribute(Constants.Document.DOCUMENT_TYPE, DocumentType.DELIVERYNOTE.toString()));
                            objectAttributes.add(new ObjectAttribute(Constants.Document.DOCUMENT_NO, seqNumber));
                            objectAttributes.add(new ObjectAttribute(Constants.Document.PRODUCT_ID, productId));
                            return objectCommandService.createCustomObject(new ObjectTypeTableName(Constants.ObjectTables.DOCUMENT), objectAttributes);
                        });
        CompletableFuture<Void> releaseNotesFuture =
                deliveryNoteFuture
                        .thenComposeAsync(deliveryNoteId -> joinReleaseNotesWithDeliveryNote(deliveryNoteId, releaseNotesIds));

        CompletableFuture<Void> parcelsFuture =
                deliveryNoteFuture
                        .thenComposeAsync(deliveryNoteId -> changeParcelsStatusForReleaseNotes(releaseNotesIds));

        return deliveryNoteFuture;
    }

如果releaseNotesFuture或parcelsFuture中的任何一个异常完成,我怎么能等待releaseNotesFuture和parcelsFuturecompletion然后返回deliveryNoteFuture结果或错误?

解决方法:

而不是返回deliveryNoteFuture,您必须拥有一个CompletableFuture,它在releaseNotesFuture和parcelsFuture完成时完成.此外,您将希望未来然后组成deliveryNoteFuture的结果,因为如果整个链成功,您需要它的ObjectId.

就像是

return CompletableFuture.allOf(releaseNotesFuture, parcelsFuture).thenComposeAsync(r -> deliveryNoteFuture);

由于releaseNotesFuture和parcelsFuture都依赖于deliveryNoteFuture,因此来自deliveryNoteFuture的错误将传播通过所有这些链.

同样,如果releaseNotesFuture或parcelsFuture中的任何一个失败,则CompletableFuture returned by allOf将在该失败的原因下完成,并且该原因将传播到thenComposeAsync返回的将来.否则,将传递deliveryNoteFuture的结果.

作为Holger suggests,因为你只有这两个期货,你也可以使用thenCombine

releaseNotesFuture.thenCombineAsync(parcelsFuture, (x, y) -> deliveryNoteFuture.join());

这里,join()不会阻塞,因为deliveryNoteFuture肯定已经完成.同样,如果deliveryNoteFuture最初失败,其原因将沿着以thenCombineAsync返回的CompletableFuture结尾的链传播.

标签:completable-future,java,java-8
来源: https://codeday.me/bug/20190828/1751677.html