Skip to content

Commit

Permalink
Added a helper method to FinallyRunAll
Browse files Browse the repository at this point in the history
  • Loading branch information
Aklakan committed Mar 2, 2024
1 parent deb74d6 commit 3a530e6
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,12 @@
import io.reactivex.rxjava3.core.Flowable;
import io.reactivex.rxjava3.core.Single;

/**
* A lookup service builds a cold flowable that upon execution retrieves data for the given set of keys.
*
* @param <K>
* @param <V>
*/
public interface LookupService<K, V>
extends Function<Iterable<K>, Flowable<Entry<K, V>>> //CompletableFuture<Map<K, V>>>
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,11 @@

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.function.Consumer;
import java.util.stream.Collectors;

import org.aksw.commons.util.function.ThrowingRunnable;

Expand Down Expand Up @@ -84,4 +87,47 @@ protected void runAction(int index) {
public static void run(ThrowingRunnable ... actions) {
new FinallyRunAll(Arrays.asList(actions)).run();
}

public static <T> void runAll(Collection<T> actions, Consumer<T> runner, ThrowingRunnable finallyAction) {
ThrowingRunnable[] runnables = actions.stream().map(action -> {
ThrowingRunnable r = () -> {
runner.accept(action);
};
return r;
}).collect(Collectors.toList()).toArray(new ThrowingRunnable[0]);

try {
run(runnables);
} finally {
if (finallyAction != null) {
try {
finallyAction.run();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}

// Alternative approach using a loop
if (false) {
List<Exception> exceptions = null;
for (T action : actions) {
try {
runner.accept(action);
} catch (Exception e) {
if (exceptions == null) {
exceptions = new ArrayList<>();
}
exceptions.add(e);
}
}

if (exceptions != null) {
RuntimeException e = new RuntimeException();
exceptions.forEach(e::addSuppressed);
throw e;
}
}
}

}

0 comments on commit 3a530e6

Please sign in to comment.