I wrote the following snipet code within Cumulocity platform.
runForTenant
must be in a separate thread. What is your an opinion about my code. is there any need for optimization? Thanks
LinkedList<CompletableFuture<Void>> asyncThreads = new LinkedList<CompletableFuture<Void>>();
CompletableFuture<Iterable<ManagedObjectRepresentation>> response = new CompletableFuture<>();
subscriptions.runForEachTenant(() -> {
String tenant = subscriptions.getTenant();
asyncThreads.add(CompletableFuture.runAsync(() -> {
subscriptions.runForTenant(tenant, () -> {
Iterable<ManagedObjectRepresentation> objects = inventoryApi
.getManagedObjectsByFilter(customInventoryFilter).get().allPages();
if (!ObjectUtils.isEmpty(objects)) {
response.complete(objects);
}
});
})); // end of runAsync()
});
boolean allThreadsAreDone = true;
do { // until all threads are done ...
try {
return response.get(50, TimeUnit.MILLISECONDS); // wait for first result
} catch (TimeoutException e) {
// device with UUID Not found in time
// check all threads are done/closed/stopped in all fashions
allThreadsAreDone = true;
for (int i = 0; allThreadsAreDone && i < asyncThreads.size(); i++) {
allThreadsAreDone = asyncThreads.get(i).isDone();
}
} catch (ExecutionException execExc) {
logger.error("Error on lookup: " + execExc.getLocalizedMessage());
} catch (InterruptedException interExc) {
logger.error("Error on lookup: " + interExc.getLocalizedMessage());
}
} while (!allThreadsAreDone);
I want to optimize the last path of the code:
boolean allThreadsAreDone = true;
do { // until all threads are done ...
try {
return response.get(50, TimeUnit.MILLISECONDS); // wait for first result
} catch (TimeoutException e) {
// device with UUID Not found in time
// check all threads are done/closed/stopped in all fashions
allThreadsAreDone = true;
for (int i = 0; allThreadsAreDone && i < asyncThreads.size(); i++) {
allThreadsAreDone = asyncThreads.get(i).isDone();
}
} catch (ExecutionException execExc) {
logger.error("Error on lookup: " + execExc.getLocalizedMessage());
} catch (InterruptedException interExc) {
logger.error("Error on lookup: " + interExc.getLocalizedMessage());
}
} while (!allThreadsAreDone);
subscriptions::runForEachTenant
do? Executes aRunnable
? Naming suggests it should execute aFunction
or aConsumer
oftenant
. \$\endgroup\$