JDK-6450279 : InetAddress GetHostName() method takes long time in windows - need timeout option
  • Type: Enhancement
  • Component: core-libs
  • Sub-Component: java.net
  • Affected Version: 5.0u7
  • Priority: P3
  • Status: Closed
  • Resolution: Not an Issue
  • OS: windows_2003
  • CPU: x86
  • Submitted: 2006-07-19
  • Updated: 2011-12-28
  • Resolved: 2006-10-03
When java InetAddress getHostName() method is used to do reverse DNS lookup for the host ip addresses, for ip addresses with incorrect/missing dns entries, getHostName() method takes more than 13 seconds in windows platform. When reverse lookup is done for more than two lakh ipaddresses, the processes run for a long time without any option to timeout the method.
Since this getHostName() method call is a blocking call, need a mechanism to have timeout if it takes more time.

EVALUATION Adding a timeout to InetAddress.getHostName is not that useful as most applications will fail if the lookup fails, and this certainly cannot be add to tiger. Changing the API in an update is not allowable. A better solution is to write a simply executor to do the job, see the "workaround" section for an example of this.

WORK AROUND -- A simple workaround is to do the lookup in a background thread, or better still use an Executor such as that in the following example: import java.net.InetAddress; import java.net.UnknownHostException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; import java.util.concurrent.Future; import java.util.concurrent.FutureTask; import java.util.concurrent.Callable; import java.util.concurrent.TimeUnit; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeoutException; public class Test { static class LookupService { ExecutorService executor; private LookupService() { executor = Executors.newSingleThreadExecutor(new ThreadFactory() { public Thread newThread(Runnable r) { Thread t = new Thread(r); t.setDaemon(true); return t; } }); } static LookupService create() { return new LookupService(); } Future<InetAddress> getByName(final String host) { FutureTask<InetAddress> future = new FutureTask(new Callable<InetAddress>() { public InetAddress call() throws UnknownHostException { return InetAddress.getByName(host); } }); executor.execute(future); return future; } } public static void main(String[] args) throws Throwable { LookupService service = LookupService.create(); Future<InetAddress> future = service.getByName(args[0]); InetAddress ia = future.get(10L, TimeUnit.SECONDS); } } This example creates a LookupService. The getByName method returns a Future with the pending result of the lookup. The application invokes the get method to wait for the result. In this example, if the lookup does not complete in 10 seconds then a TimeoutException is thrown.

WORK AROUND No known workaround *** (#1 of 1): [ UNSAVED ] ###@###.###