1

In the Main class i am trying to run tasks asynchronously using CompletableFuture. and as shown in the code of FMSMsgHandlerSupplier class, it returns data of type Double[]

the problem is, in the for-loop of the Main class the FMSMsgHandlerSupplier is called 5 times and lets assume that for each iteration i am receiving new value of data type Double[], how can i get the result computed after each call to FMSMsgHandlerSupplier class?

Main:

public class Main {

private final static String TAG = Main.class.getSimpleName();

public static void main(String[] args) throws InterruptedException, ExecutionException {

    CompletableFuture<Double[]> compFuture = null;
    for (int i = 0; i < 5; i++) {
        compFuture = CompletableFuture.supplyAsync(new FMSMsgHandlerSupplier(1000 + (i*1000), "1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12"));
    }
}

}

FMSMsgHandlerSupplier:

public class FMSMsgHandlerSupplier implements Supplier<Double[]>{

private final static String TAG = FMSMsgHandlerSupplier.class.getSimpleName();
private String mFMSMsg = ""; 
private static long sStartTime = TimeUtils.getTSMilli();
private int mSleepTime;

public FMSMsgHandlerSupplier(int sleepTime, String fmsMsg) {
    // TODO Auto-generated constructor stub
    this.mFMSMsg = fmsMsg;
    this.mSleepTime = sleepTime;
}

public Double[] get() {
    // TODO Auto-generated method stub
    if (this.mFMSMsg != null && !this.mFMSMsg.isEmpty()) {

        Double[] inputMeasurements = new Double[9];

        String[] fmsAsArray = this.toArray(this.mFMSMsg);
        inputMeasurements = this.getInputMeasurements(fmsAsArray);

        return inputMeasurements;

    } else {
        Log.e(TAG, "FMSMsgHandler", "fmsMsg is null or empty");

        return null;
    }
}
Amrmsmb
  • 1
  • 27
  • 104
  • 226

1 Answers1

1

You could use the get() method of completable future to get the value. But that would mean your loop will wait until the value is returned. A better fit would be one of thenAccept, thenRun...etc methods. For example,

public static void main(String[] args) {
    List<CompletableFuture> compFutures = new ArrayList<>();
    //timeout in seconds
    int TIMEOUT = 120; //or whatever
    for (int i = 0; i < 5; i++) {
    CompletableFuture<Double[]> compFuture = CompletableFuture.supplyAsync(new FMSMsgHandlerSupplier(1000 + (i*1000), "1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12"));
        compFuture.thenAcceptAsync(d -> doSomethingWithDouble(d));
        compFutures.add(compFuture);    
    }
    CompletableFuture.allOf(compFutures).get(TIMEOUT, TimeUnit.SECONDS);
}

public static void doSomethingWithDouble(Double[] d) {
    System.out.print(d);
}