简体   繁体   中英

What is a good design pattern of interfacing with asynchronous API in Java

I need to chain a sequence of proprietary async APIs calls in Java.

I put something together that works ( for a happy case at least) , but can't think of a better way to organize this this code. I wonder if there is a design pattern or a library that can wrap the ugliness in a nice set of APIs or a library. Something similar to , js promises or async in c++. Thanks !!

Here is what I currently do :

// call API1
api.send(...., new myMethodCallbackHandler()));

        while (myAtomicFlag.get() == 0) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        if (myAtomicFlag.get() == 1){
            // success 
            successFlag = true;
            myAtomicFlag.set(0);
            .. do more success stuff
            // call API2
        }else{
            successFlag = false;
            // handle problems
        }
}

Currently, Java does not support async/await, but Kotlin does, so you can write this piece of code in Kotlin, while the rest of your program can stay in Java.

Java has, however, an equivalent of js promise: CompletableFuture. It can be used for your task in the following way:

for (API api: apilist) {
  MyMethodCallbackHandler handler = new MyMethodCallbackHandler();
  api.send(...., handler);
  try {
    Object result = handler.get();
    .. do more success stuff
  } catch (Throwable ex) {
    // handle problems
  }
}

I assume the callback handler has to implement following interface:

interface CallbackHandler {
   void onSuccess(Object result);
   void onError(Throwable error);
}

then the class MyMethodCallbackHandler can be declared as:

class MyMethodCallbackHandler extends CompletableFuture implements CallbackHandler {
   void onSuccess(Object result) {
      super.complete(result);
   }
   void onError(Throwable error) {
      super.completeExceptionally(error);
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM