If you’re going to fiddle with networkaddress.cache.ttl, do it before you touch the network.
I was using the java.net.InetAddress class to resolve IP addresses from DNS names the other day.
I wanted to test my code by manipulating my local system’s ‘hosts’ file, to quickly simulate moving IP addresses around behind a DNS name, so I also set disabled caching the resolved addresses from one call to the next by programmatically setting the networkaddress.cache.ttl Security property to ‘0’. According to the javadocs,
The value [assigned to networkaddress.cache.ttl] is specified as as integer to indicate the number of seconds to cache the successful lookup.
which is true, and everything was peachy – my hosts file changes were immediately picked up.
At first.
I continued to build my code and all of a sudden, the caching came back and the changes I was making in my hosts file were ignored.
By backtracking my changes, I worked out that the breaking change happened when I executed a network call which involved name resolution BEFORE I disabled the cache.
I moved the setting of the property to happen before I touched the network et voila – everything peachy again.
This (feature|problem|bug) is documented in a couple of places when you know what you’re looking for, like here.
And here’s a simple code demo of it in action:
public static void main(String[] args) throws Exception {
String name = "google.com";
//lookup(name);
Security.setProperty("networkaddress.cache.ttl", "0");
while (true) {
lookup("google.com");
Thread.sleep(1000);
}
public static void lookup(String name) throws Exception {
System.out.println(name + ":" + InetAddress.getByName(name).getHostAddress());
}
}
Running the sample above as-is:
google.com:74.125.127.100
google.com:74.125.67.100
google.com:74.125.127.100
google.com:74.125.67.100
google.com:74.125.127.100
But uncomment the first call to lookup(), and
google.com:74.125.45.100
google.com:74.125.45.100
google.com:74.125.45.100
google.com:74.125.45.100
google.com:74.125.45.100
Cheers,