CUBは子供の白熊

Java SE 8 実践プログラミングの練習問題を解く

第3章 ラムダ式を使ったプログラミング : 問題 16 : ラムダ式と例外

問題

first が生成した結果を second が消費し、その間に発生したエラーを handler が処理するメソッド

public static <T> void doInOrderAsync(Supplier<T> first, Consumer<T> second,
    Consumer<Throwable> handler)
{
    new Thread(
        () ->  {
            try {
                T result = first.get();
                second.accept(result);
            } catch (Throwable th) {
                handler.accept(th);
            }
        }
    ).start();
}

を元にして

void doInOrderAsync(Supplier<T> first, BiConsumer<T, Throwable> second)

を実装せよ

解答

second は、first が成功したケースもエラーが起こったケースも、同じaccept(T, Throwable)メソッドで処理する

エラーが起こったかどうかは

Throwablenull

で判定する

public static <T> void doInOrderAsync(Supplier<T> first, BiConsumer<T, Throwable> second) {
    new Thread(
        () ->  {
            T result = null;
            try {
                result = first.get();
                second.accept(result, null);
            } catch (Throwable th) {
                second.accept(result, th);
            }
        }
    ).start();
}

さらに問題

これのうまいユースケースを示せ

解答

ごめんなさい
つまんないユースケースは浮かぶけど “うまい” ユースケースは浮かびません

思い付いたら更新するので、今回はパス