One solution is to execute the DNS resolution on a different thread which is given only a certain amount of time to complete.
Here's a simple utility that can help you do this:
public class TimeSliceExecutor {
public static class TimeSliceExecutorException extends RuntimeException {
public TimeSliceExecutorException(String message, Throwable cause) {
super(message, cause);
}
}
public static void execute(Runnable runnable, long timeoutInMillis) {
ExecutorService executor = Executors.newSingleThreadExecutor();
try {
Future<?> future = executor.submit(runnable);
getFuture(future, timeoutInMillis);
}
finally {
if (executor != null) {
executor.shutdown();
}
}
}
public static <T> T execute(Callable<T> callable, long timeoutInMillis) {
ExecutorService executor = Executors.newSingleThreadExecutor();
try {
Future<T> future = executor.submit(callable);
return getFuture(future, timeoutInMillis);
}
finally {
if (executor != null) {
executor.shutdown();
}
}
}
public static <T> T getFuture(Future<T> future, long timeoutInMillis) {
try {
return future.get(timeoutInMillis, TimeUnit.MILLISECONDS);
}
catch (InterruptedException ex) {
Thread.currentThread().interrupt();
throw new TimeSliceExecutorException("Interrupton exception", ex);
}
catch (ExecutionException ex) {
throw new TimeSliceExecutorException("Execution exception", ex);
}
catch (TimeoutException ex) {
throw new TimeSliceExecutorException(String.format("%dms timeout reached", timeoutInMillis), ex);
}
}
}
Then build the socket along these lines:
private Socket buildSocket() throws IOException {
final Socket socket = new Socket();
socket.setSoTimeout(socketTimeout);
socket.connect(new InetSocketAddress(resolveHost(host, dnsTimeout), port), connectionTimeout);
return socket;
}
private static InetAddress resolveHost(String host, long dnsTimeout) throws IOException {
try {
return TimeSliceExecutor.execute(() -> InetAddress.getByName(host), dnsTimeout);
}
catch (TimeSliceExecutor.TimeSliceExecutorException ex) {
throw new UnknownHostException(host);
}
}
Ref: https://stackoverflow.com/a/70610305/225217