Не получается результат: работа с завершаемым будущим - PullRequest
0 голосов
/ 01 июля 2019

Я предполагаю получить ответ от двух API, а затем только двигаться вперед. Чтобы достичь этого, пытался использовать завершаемое будущее, но в итоге получал исключение NullPointerException при получении ответа от объекта «результат». Infact, completeableFuture в основном не имеют данных. Не удалось отладить поток, работающий напрямую.

public APIResult execute() throws InterruptedException, ExecutionException {

        CompletableFuture<TaskChair> completableFutureChair = CompletableFuture.supplyAsync(()->new TaskChair(),executorChair);
        CompletableFuture<TaskBottle> completableFutureBottle = CompletableFuture.supplyAsync(()->new TaskBottle(),executorChair);


        CompletableFuture<Void> combinedFuture = CompletableFuture.allOf(completableFutureChair, completableFutureBottle);
        combinedFuture.get();

        TaskChair taskChair = completableFutureChair.get();
        TaskBottle taskBottle = completableFutureBottle.get();

        List<Chair> chairs = taskChair.getChairs();
        List<Bottle> bottles = taskBottle.getBottles();

        APIResult result = new APIResult(chairs, bottles);

        return result;
    }


class TaskChair implements Callable<List<Chair>>{

    List<Chair> chairs;

    public List<Chair> getChairs() {
        return chairs;
    }
    public void setChairs(List<Chair> chairs) {
        this.chairs = chairs;
    }

    @Override
    public List<Chair> call() throws Exception {
        chairs = new RestAPI().getChairs();
        return chairs;
        }
    }

public static void main(String[] args) {

        RestService service = new RestService();
        APIResult result = null;

        try {
            result = service.execute();
        } catch (InterruptedException | ExecutionException e) { }

        System.out.println("Chair API Status -> ");
        for(Chair chair:result.getChairs()) {
            System.out.println(" id : "+chair.getId()+" name : "+ chair.getName());
        }
    }
...