The example in this article describes the method of cleaning DNS Cache in Java. Share it with everyone for your reference. The specific analysis is as follows:
1. Test environment
OS: Windows7 x64
JDK: 1.6.0_45
2. I found four ways to clear the DNS cache of jvm. You can choose according to your own situation.
1. Before calling InetAddress.getByName() for the first time, set java.security.Security.setProperty("networkaddress.cache.ttl", "0");
2. Modify the networkaddress.cache.ttl property under jre/lib/security/java.security
3. Set -Dsun.net.inetaddr.ttl=0 in the jvm startup parameters
4. Cleaning through reflection, such as the clearCache method in this article
3. Code
Copy the code as follows: package xiaofei;
import java.lang.reflect.Field;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Map;
/**
* @author xiaofei.wxf
* @date 13-12-18
*/
public class DNSCacheTest {
/**
* 1. Before calling InetAddress.getByName() for the first time, set java.security.Security.setProperty("networkaddress.cache.ttl", "0");
* 2. Modify the networkaddress.cache.ttl property under jre/lib/security/java.security
* 3. Set -Dsun.net.inetaddr.ttl=0 in jvm startup parameters
* 4. Call clearCache method to clear
*
* @param args
* @throws UnknownHostException
*/
public static void main(String[] args) throws UnknownHostException, NoSuchFieldException, IllegalAccessException {
java.security.Security.setProperty("networkaddress.cache.ttl", "0");
InetAddress addr1 = InetAddress.getByName("www.baidu.com");
System.out.println(addr1.getHostAddress());
//clearCache();
//Set a breakpoint on the next line.
//It is invalid to put it here, because this value is determined when the class is loaded (it should be set before using InetAddress.getByName) and has been cached.
//java.security.Security.setProperty("networkaddress.cache.ttl", "0");
InetAddress addr2 = InetAddress.getByName("www.baidu.com");
System.out.println(addr2.getHostAddress());
InetAddress addr3 = InetAddress.getByName("www.google.com");
System.out.println(addr3.getHostAddress());
InetAddress addr4 = InetAddress.getByName("www.google.com");
System.out.println(addr4.getHostAddress());
//clearCache();
}
public static void clearCache() throws NoSuchFieldException, IllegalAccessException {
//Start modifying cache data
Classclazz = java.net.InetAddress.class;
final Field cacheField = clazz.getDeclaredField("addressCache");
cacheField.setAccessible(true);
final Object obj = cacheField.get(clazz);
Class cacheClazz = obj.getClass();
final Field cachePolicyField = cacheClazz.getDeclaredField("type");
final Field cacheMapField = cacheClazz.getDeclaredField("cache");
cachePolicyField.setAccessible(true);
cacheMapField.setAccessible(true);
final Map cacheMap = (Map)cacheMapField.get(obj);
System.out.println(cacheMap);
cacheMap.remove("www.baidu.com");
}
}
I hope this article will be helpful to everyone’s Java programming.