问题
Where check/set timeout when java.net.UnknownHostException is thrown?
Occasionally my code tries to connect to a non-existing location and throws java.net.UnknownHostException what is acceptable case in my app.
The problem I have is that it takes roughly about 20sec before the exception is thrown and it slows down the whole application.
The webserver version is Tomcat 7.0.37. I have tried change timeout settings (to 2sec) in the server.xml for following connectors:
Connector port="8009" protocol="AJP/1.3" redirectPort="8443" connectionTimeout="2000"
Connector port="8080" protocol="HTTP/1.1" connectionTimeout="2000" redirectPort="8443"
As I use HttpURLConnection I would expect the connection timeout setting for port 8080 to take effect, but it does not seem to be true.
I also tried to set the timeout within the code:
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setConnectTimeout(1000);
Reader reader= new InputStreamReader((InputStream) connection.getContent());
But this did not work neither, any ideas? Am I missing something?
ta
回答1:
The time is probably being spent looking up the host in DNS, which in your case seems to be timing out when trying to look up a host that can't be found. This happens if the DNS server you connect to forwards the request to another DNS server, and doesn't get a reply in a reasonable amount of time, perhaps because it's not well configured.
You can solve this problem in the operating system level by making the DNS lookup timeout earlier; for example in Linux you could add options timeout:2
to /etc/resolv.conf
to make DNS lookups timeout in 2 seconds instead of the default. On Windows you have to edit a registry setting.
Alternatively you can solve this in your program by using a thread for the name resolution. If the thread doesn't return in a timeout you specify you assume that name resolution will throw an UnknownHostException
.
A third option is using a different, better behaved DNS server, like the ones maintained by Google at 8.8.8.8 and 4.4.4.4.
回答2:
The problem you are facing is a DNS resolution problem not a Java one, I guess that your program is blocked during the DNS query. Try to perform an nslookup on an unknown host inside a shell to see if you reproduce the problem. If you are, ask your system administrator to look at the DNS server logs and configuration if there's something wrong.
If the hosts are frequently the same, look at this post to configure the negative ttl to cache the Unknown host responses from the DNS : any-way-to-make-java-honor-the-dns-caching-timeout-ttl
来源:https://stackoverflow.com/questions/16605784/where-check-set-timeout-when-java-net-unknownhostexception-is-thrown