5

I'm attempting to change the DNS cache timeout in Java 1.6. I see discussion here of using something like the following:

java.security.Security.setProperty ("networkaddress.cache.ttl" , TTL_SECS);

But I've tried this simple test in Win 7....

System.out.println("DEFAULT DNS TTL: "+sun.net.InetAddressCachePolicy.get());
java.security.Security.setProperty ("networkaddress.cache.ttl" , "123");    
System.out.println("DEFAULT DNS TTL: "+sun.net.InetAddressCachePolicy.get());

... and the output doesn't change. It seems this can be changed in the Java installation's security properties but I preffer to keep this in the code for neatness. Any ideas how to achieve that?

Thanks.

Jonathan
  • 1,327
  • 3
  • 15
  • 24
  • The very link you cited suggests that "setProperty()" ("Option #2") doesn't work. Q: Did you try "Option#1" (edit jre/lib/security/java.security)? What did you find? What Java version are you using? – paulsm4 Aug 23 '12 at 20:38
  • True, I seem to have confirmed what a commenter said. Haven't tried option #1 from the link, would much rather this was in code not config. I'm using 1.6 – Jonathan Aug 23 '12 at 20:40

3 Answers3

14

Try this and see the output you get. The property needs to be set when the class is loaded.

static {
    java.security.Security.setProperty ("networkaddress.cache.ttl" , "12");    
}
public static void main(String[] args) {
    System.out.println("DEFAULT DNS TTL: "+sun.net.InetAddressCachePolicy.get());
    java.security.Security.setProperty ("networkaddress.cache.ttl" , "123");    
    System.out.println("DEFAULT DNS TTL: "+sun.net.InetAddressCachePolicy.get());
}
Ravi Nori
  • 149
  • 1
  • 3
  • Would this be OK for Spring Boot 2 app? I put a println and it seems this is executed 2 times. Would that be a problem? Also if i try to put it in @ Configuration class it seems println executes after Hikari connects to the DB. UPDATE:It seems it was executed twice because i used spring-boot-devtools – alext Jan 02 '21 at 11:40
3

These are not system properties: they are set in the java.security file. For the corresponding system properties, which are non-preferred, see 'Sun implementation-specific properties' in Networking Properties.

user207421
  • 305,947
  • 44
  • 307
  • 483
  • Correct. For a full list of ways to set DNS caching TTL (including as a -D flag or system property), see http://stackoverflow.com/questions/1256556/any-way-to-make-java-honor-the-dns-caching-timeout-ttl. – Jon Onstott Jan 21 '16 at 20:20
0

In Android 4.0 (Ice Cream Sandwich) and earlier, DNS caching was performed both by InetAddress and by the C library, which meant that DNS TTLs could not be honored correctly. In later releases, caching is done solely by the C library and DNS TTLs are honored.

Google desc

lingyfh
  • 1,363
  • 18
  • 23