首页 > 解决方案 > 使用 CompleteableFuture 异步执行两个方法

问题描述

这是我必须使运行速度更快的代码片段:

fillPricedServiceForLocation(location, doc, locale, services);

fillReviewsForLocation(location, doc, services);

两种方法如下所示:

private static void fillPricedServiceForLocation(Location location, LocationDocument doc,
    Language locale, List<Long> services) {
    if (doc.isPriceList()) {
        String locationId = doc.getLocationId();
        try {
            new PricesRepository().findServiceForLocation(locationId, services)
                .ifPresent(foundService -> {
                    String serviceId = foundService.getServiceId();
                    final LocationServices locationServices = new LocationServices();
                    locationServices.setId(Integer.valueOf(serviceId));
                    locationServices.setPrice(BigDecimal.valueOf(foundService.getPrice()));
                    locationServices.setCurrency(foundService.getCurrency());

                    ServiceName serviceName = ServiceNameProvider.getServiceName(serviceId);
                    locationServices.setName(serviceName.getName(locale));
                    location.setServices(locationServices);
                });
        } catch (Exception e) {
            log.error("Error when trying to retrieve last review for location {}", locationId,
                      e);

        }
    }
}

private static void fillReviewsForLocation(Location location, LocationDocument doc,
    List<Long> services) {
    String locationId = doc.getLocationId();
    try {
        LocationReviews locationReviews = new LocationReviews();
        locationReviews.setCount(doc.getReviewsCount());
        locationReviews.setScore(doc.getReviewsScore());

        new ReviewsRepository().findReview(locationId, services).ifPresent(
            foundReview -> locationReviews.setReview(reviewDocumentToJsonModel(foundReview)));
        location.setReviews(locationReviews);
    } catch (Exception e) {
        log.error("Error when trying to retrieve last review for location {}", locationId, e);
    }
}

他们调用两个不同的存储库,如果他们找到一些东西,他们会处理它并更新作为参数location传递。是否可以并行化这两个方法调用以便同时处理它们?尝试使用 CompleteableFuture 但无法使其运行 - 对异步编程没有太多经验。

标签: javaasynchronous

解决方案


你可以在两个不同的线程中,在每个线程的 run() 方法中编写一个函数。然后使用 ExecutorService.submit(threadOne) 和 ExecutorService.submit(threadTwo) 并行执行它。


推荐阅读