Java HttpHandler 等待 CompletableFuture

问题描述

我得到以下代码

public WebClient extends WebSocketClient{
...
    private StringBuilder response;
    
    public WebClient(StringBuilder response){
        this.response = response;
    }
    
    public void onMessage(ByteBuffer bytes
    
        CompletableFuture<Void> completableFuture  = CompletableFuture.
            supplyAsync(this::fsupplyAsync)
            .thenApply(this::fThenApply)
            }).exceptionally(t -> {
                return fexceptionally(t);
            }).thenAccept(x -> {
                fthenAccept(x);
            });

        completableFuture.get();
        this.setDone(true);
    
    }
    
...
}

public class handler implements HttpHandler { 
...

    public void handle(HttpExchange httpExchange) throws IOException {
        
        ByteBuffer message;
        ...
        StringBuilder response = new StringBuilder();
        
        WebClient client = new WebClient(response);
        
        client.send(message);
        
        while(!client.isDone()){
            Thread.sleep(2000);
        }
        
        httpExchange.getResponseHeaders().add("Access-Control-Allow-Origin","*");
        final byte[] responseBytes = response.getBytes();
        httpExchange.sendResponseHeaders(200,responseBytes.length);
        outputStream.write(responseBytes);
    }
    
... 
}

这个想法是我调用另一个客户端获取一些信息,等待他的响应,然后呈现已经接收和处理的数据。

但我正在寻找一种方法来避免需要 Thread.sleep 以避免系统中其他代码可能出现的问题。

在我将结果写入处理程序之前,是否有另一种方法可以等待 WebClient 中可比较的未来调用的结果?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)