Pre JDK6 Java would by default cache successful DNS lookups for ever. In JDK 6 & 7 it caches for 30 seconds by default or forever when running under a security manager. You can override the defaults by setting some security properties as specified in InetAddress
.
I wanted to check what the settings were for my server. The security properties weren’t set and Maven wouldn’t compile my code when I tried to reference sun.net.InetAddressCachePolicy
.
Here’s some fairly nasty code that uses reflection that will give you access to what you want. This worked in JDK6u43 but as it relies on private fields there’s no guarantee it will work on any other version of Java.
final Field dnsCacheField = InetAddress.class.getDeclaredField("addressCache");
dnsCacheField.setAccessible(true);
final Object dnsCache = dnsCacheField.get(null);
dnsCacheField.setAccessible(false);
final Method cachePolicyGetter = dnsCache.getClass().getDeclaredMethod("getPolicy", new Class [0]);
cachePolicyGetter.setAccessible(true);
final Object cachePolicy = cachePolicyGetter.invoke(dnsCache);
cachePolicyGetter.setAccessible(false);
if (((Number) cachePolicy).intValue() == -1) {
logger.error("Infinite DNS cache policy enabled. Likely to cause issues.");
} else {
logger.info("DNS cache set to:" + cachePolicy);
}
You might want to wrap it in a try-catch block.