0

There is an asynchronous construction. I would like to continue processing after reading from the database here. I tried to use the "while" cycle as follows, but it didn't. Endless loop. If there is no "while" loop, it is asynchronous, but it doesn't work for me.

private XmlOperations fetchAttributeFromDB(RequestContext context, 
                   XmlOperations invCnclAttributes,String orderId) {

    String strSQL = "select bankStan,bankBatch,provBank from transactionHistory where orderId='"+orderId+"' limit 1";
    DBClientService dbClientService = DBClientService.getService(context);
    try {
        Future<List<JsonArray>> futureHistory = dbClientService.ExecuteQuery(strSQL);
        futureHistory.setHandler(sqlResult -> {
            List<JsonArray> result = futureHistory.result();
            invCnclAttributes.addAttribute("bankStan", result.get(0).getString(0));
            invCnclAttributes.addAttribute("bankBatch", result.get(0).getString(1));
            invCnclAttributes.addAttribute("provBank", result.get(0).getString(2));
            futureHistory.complete();
        });
        while(!futureHistory.isComplete());
    }catch(Exception e){
        e.printStackTrace();
    }
    return invCnclAttributes;
}
Yusuf Koçak
  • 109
  • 1
  • 1
  • 14
  • `Future` should already be fully synchronized. – markspace May 23 '19 at 16:00
  • 1
    As you know, "Future" is asynchronous. That's the whole point. It sounds like all you need is to add a `future.get()`. Do *NOT* use a "polling loop"! Get rid of that "while()"!!! ALSO: look here: https://www.baeldung.com/java-completablefuture – paulsm4 May 23 '19 at 16:00
  • 2
    If you really want to block/wait here, you can do `futureHistory.get()`. But the preferred way is to produce another Future using `thenApply` or `thenCompose`. `Future results = futureHistory.thenApply(result -> new TheThreeAttributes(result.get(0).getString(0), .....)` – Thilo May 23 '19 at 16:04

1 Answers1

0

You don't say if you can use Java 8 (which supports CompletableFuture and Streams) or Java 9 (which also supports the "Reactive" Flow API).

Let's assume you can use Java 8 and feel reasonably comfortable with Futures.

Then you want to use CompletableFuture. And, as Thilo pointed out, you definitely want to use thenApply or thenCompose to compose your list.

Under NO circumstances do you want to use a "polling loop", if you can at all avoid it.

Here is an excellent, short tutorial that will tell you the basic concepts, and give you example code:

Baeldung: Guide To CompletableFuture

Here is a book I've personally found very useful for understanding the new Java concurrency APIs:

Modern Java in Action: Lambdas, streams, functional and reactive programming 2nd Edition

<= The 2nd edition also covers Java 9 and Java 10

paulsm4
  • 114,292
  • 17
  • 138
  • 190