Skip to content

Commit

Permalink
Add shutdown hook to close AsyncHttpClient. Add Threadfactory to Asyn…
Browse files Browse the repository at this point in the history
…cHttpClient to update threadfactory to use daemon threads. (#8763)

Co-authored-by: Diego Molina <diemol@users.noreply.github.com>
  • Loading branch information
pujagani and diemol committed Oct 13, 2020
1 parent 5a189b9 commit cc1ac60
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 7 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -23,5 +23,6 @@ java_library(
artifact("io.netty:netty-transport-native-kqueue"),
artifact("io.netty:netty-transport-native-kqueue-osx-x86_64"),
artifact("io.netty:netty-transport-native-unix-common"),
artifact("io.netty:netty-common"),
],
)
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
package org.openqa.selenium.remote.http.netty;

import com.google.auto.service.AutoService;

import io.netty.util.concurrent.DefaultThreadFactory;
import org.asynchttpclient.AsyncHttpClient;
import org.asynchttpclient.DefaultAsyncHttpClientConfig;
import org.asynchttpclient.Dsl;
Expand All @@ -32,16 +32,20 @@
import org.openqa.selenium.remote.http.HttpResponse;
import org.openqa.selenium.remote.http.WebSocket;

import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.BiFunction;
import java.io.IOException;

public class NettyClient implements HttpClient {

private static final AsyncHttpClient httpClient = Dsl.asyncHttpClient(
new DefaultAsyncHttpClientConfig.Builder()
.setUseInsecureTrustManager(true)
.setAggregateWebSocketFrameFragments(true)
.setWebSocketMaxBufferSize(Integer.MAX_VALUE)
.setWebSocketMaxFrameSize(Integer.MAX_VALUE));
private static final AsyncHttpClient httpClient =
Dsl.asyncHttpClient(
new DefaultAsyncHttpClientConfig.Builder()
.setThreadFactory(new DefaultThreadFactory("AsyncHttpClient", true))
.setUseInsecureTrustManager(true)
.setAggregateWebSocketFrameFragments(true)
.setWebSocketMaxBufferSize(Integer.MAX_VALUE)
.setWebSocketMaxFrameSize(Integer.MAX_VALUE));

private final HttpHandler handler;
private BiFunction<HttpRequest, WebSocket.Listener, WebSocket> toWebSocket;
Expand Down Expand Up @@ -76,6 +80,23 @@ public HttpClient with(Filter filter) {
@HttpClientName("netty")
public static class Factory implements HttpClient.Factory {

private static final AtomicBoolean addedHook = new AtomicBoolean();

public Factory() {
if (!addedHook.get()) {
Runtime.getRuntime().addShutdownHook(new Thread(this::callAsyncClientShutdown));
addedHook.set(true);
}
}

private void callAsyncClientShutdown() {
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}

@Override
public HttpClient createClient(ClientConfig config) {
Require.nonNull("Client config", config);
Expand Down

0 comments on commit cc1ac60

Please sign in to comment.