AsynHelper Javaライブラリには、このような非同期呼び出し(および待機)のためのユーティリティクラス/メソッドのセットが含まれています。
一連のメソッド呼び出しまたはコードブロックを非同期で実行する必要がある場合、以下のスニペットのように、便利なヘルパーメソッドAsyncTask .submitTasksが含まれています。
AsyncTask.submitTasks(
() -> getMethodParam1(arg1, arg2),
() -> getMethodParam2(arg2, arg3)
() -> getMethodParam3(arg3, arg4),
() -> {
//Some other code to run asynchronously
}
);
すべての非同期コードの実行が完了するまで待機する必要がある場合は、AsyncTask.submitTasksAndWaitバリアントを使用できます。
また、各非同期メソッド呼び出しまたはコードブロックから戻り値を取得する必要がある場合は、AsyncSupplier .submitSuppliersを使用して、メソッドから返された結果サプライヤー配列から結果を取得できます。以下はサンプルスニペットです。
Supplier<Object>[] resultSuppliers =
AsyncSupplier.submitSuppliers(
() -> getMethodParam1(arg1, arg2),
() -> getMethodParam2(arg3, arg4),
() -> getMethodParam3(arg5, arg6)
);
Object a = resultSuppliers[0].get();
Object b = resultSuppliers[1].get();
Object c = resultSuppliers[2].get();
myBigMethod(a,b,c);
各メソッドの戻り値の型が異なる場合は、以下の種類のスニペットを使用してください。
Supplier<String> aResultSupplier = AsyncSupplier.submitSupplier(() -> getMethodParam1(arg1, arg2));
Supplier<Integer> bResultSupplier = AsyncSupplier.submitSupplier(() -> getMethodParam2(arg3, arg4));
Supplier<Object> cResultSupplier = AsyncSupplier.submitSupplier(() -> getMethodParam3(arg5, arg6));
myBigMethod(aResultSupplier.get(), bResultSupplier.get(), cResultSupplier.get());
非同期メソッド呼び出し/コードブロックの結果は、以下のスニペットのように、同じスレッドまたは異なるスレッドの異なるコードポイントで取得することもできます。
AsyncSupplier.submitSupplierForSingleAccess(() -> getMethodParam1(arg1, arg2), "a");
AsyncSupplier.submitSupplierForSingleAccess(() -> getMethodParam2(arg3, arg4), "b");
AsyncSupplier.submitSupplierForSingleAccess(() -> getMethodParam3(arg5, arg6), "c");
//Following can be in the same thread or a different thread
Optional<String> aResult = AsyncSupplier.waitAndGetFromSupplier(String.class, "a");
Optional<Integer> bResult = AsyncSupplier.waitAndGetFromSupplier(Integer.class, "b");
Optional<Object> cResult = AsyncSupplier.waitAndGetFromSupplier(Object.class, "c");
myBigMethod(aResult.get(),bResult.get(),cResult.get());