November 1st, 2013

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

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");
    final Object dnsCache = dnsCacheField.get(null);
    final Method cachePolicyGetter = dnsCache.getClass().getDeclaredMethod("getPolicy", new Class [0]);
    final Object cachePolicy = cachePolicyGetter.invoke(dnsCache);
    if (((Number) cachePolicy).intValue() == -1) {
        logger.error("Infinite DNS cache policy enabled. Likely to cause issues.");                
    } else {"DNS cache set to:" + cachePolicy);

You might want to wrap it in a try-catch block.

Comments are closed.