【发布时间】:2021-07-01 20:38:33
【问题描述】:
我得到以下代码
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 中类似的未来调用的结果?
【问题讨论】:
标签: java websocket thread-safety httphandler