CompletableFuture Callback Bridge

Complete a hand-built CompletableFuture from a legacy callback thread so listener APIs join async pipelines; late duplicate callbacks cannot rewrite the result.

JavaResilience

Code

snippet
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

public class ApiBridge {

    // 第三方回调式 API:结果从它自己的线程异步送达
    interface Listener {
        void onSuccess(String value);
        void onError(Exception failure);
    }

    interface LegacyClient {
        void fetch(String key, Listener listener);
    }

    // 适配器:手工 new 一个 future,在回调里完成它,
    // 监听器式 API 就接进了 CompletableFuture 的组合管线
    static CompletableFuture<String> asFuture(LegacyClient client, String key) {
        CompletableFuture<String> future = new CompletableFuture<>();
        client.fetch(key, new Listener() {
            @Override public void onSuccess(String value) {
                future.complete(value);
            }
            @Override public void onError(Exception failure) {
                future.completeExceptionally(failure);
            }
        });
        return future;
    }

    public static void main(String[] args) throws Exception {
        LegacyClient client = (key, listener) ->
                new Thread(() -> {
                    try {
                        Thread.sleep(20);
                    } catch (InterruptedException ignored) {
                        Thread.currentThread().interrupt();
                    }
                    listener.onSuccess(key.toUpperCase());
                }).start();

        CompletableFuture<String> future = asFuture(client, "order-42");
        System.out.println(future.get(1, TimeUnit.SECONDS));

        // complete 只有第一次调用生效:迟到的重复回调改写不了结果
        System.out.println("second complete accepted: " + future.complete("late"));
        System.out.println(future.get(1, TimeUnit.SECONDS));
    }
}

What the code does

The code’s whole job belongs to the classes ApiBridge, Listener and LegacyClient and the functions asFuture, onSuccess and onError.

Applying it

Signature: static CompletableFuture<String> asFuture(LegacyClient client, String key)

The demo output is labeled (second complete accepted:), so every printed line maps back to its originating operation.

The entry point wires onSuccess and asFuture together — run it once and the whole demo flows.

Statements that matter

CompletableFuture<String> future = asFuture(client, "order-42");
CompletableFuture<String> future = new CompletableFuture<>();
Thread.currentThread().interrupt();

Interactive Tools for This Topic

FAQ

What does CompletableFuture Callback Bridge print when run?
Execute the whole file; each printed line is prefixed with a label like `second complete accepted:`.