title: disabling Java DNS cache
body: <p>I'm using Java 8 (OpenJDK). It seems like the best way to disable dns cache in Java is to set <code>networkaddress.cache.ttl=0</code> in <code>$JAVA_HOME/jre/lib/security/java.security</code>.</p>
  
  <p>I've tried that, but it seems to have no effect, no matter what value I put there, DNS entries are cached for ~5 seconds. I know that the value is set properly because I check it with <code>java.security.Security.getProperty("networkaddress.cache.ttl")</code>.</p>
  
  <p>I'm testing the java cache with a <code>HttpURLConnection</code> client, and comparing it to a raw <code>curl</code> client, curl doesn't cache at all. My server is a load balancer that returns one of 3 different ips for each request in round robin. Those ips each host a web service that returns the hostname it's running on.</p>
  
  <p>This is how the my java client looks like:</p>
  
  <pre><code>    public static void main(String[] args) throws Exception {
          System.out.println("networkaddress.cache.ttl=" + java.security.Security.getProperty("networkaddress.cache.ttl"));
          Thread.sleep(1000);
          printServerHost();
          Thread.sleep(2000);
          printServerHost();
          Thread.sleep(4000);
          printServerHost();
          Thread.sleep(6000);
          printServerHost();
          Thread.sleep(11000);
          printServerHost();
      }
  
      public static void printServerHost() throws Exception{
          URL url = new URL("http://server/");
          HttpURLConnection con = (HttpURLConnection) url.openConnection();
          con.setRequestMethod("GET");
          con.setRequestProperty("Content-Type", "application/json");
          con.setRequestProperty("Cache-Control", "no-cache");
          con.setRequestProperty("accept", "application/json");
  
          BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
          String response = reader.readLine();
          reader.close();
          con.disconnect();
  
          System.out.println(response);
      }
  </code></pre>
  
  <p>Which outputs:</p>
  
  <pre><code>networkaddress.cache.ttl=0
  ip-172-31-12-68.ec2.internal
  ip-172-31-12-68.ec2.internal
  ip-172-31-12-68.ec2.internal
  ip-172-31-41-56.ec2.internal
  ip-172-31-16-34.ec2.internal
  </code></pre>
  
  <p>And this is how my curl client looks like:</p>
  
  <pre><code>curl server
  sleep 2s
  curl server
  sleep 4s
  curl server
  sleep 6s
  curl server
  sleep 11s
  curl server
  </code></pre>
  
  <p>Which outputs:</p>
  
  <pre><code>ip-172-31-41-56.ec2.internal
  ip-172-31-16-34.ec2.internal
  ip-172-31-12-68.ec2.internal
  ip-172-31-41-56.ec2.internal
  ip-172-31-16-34.ec2.internal
  </code></pre>
  
  <p>What am I missing? Should I also configure something in <code>HttpURLConnection</code>? Another jvm wide config? Maybe it's another cache, not a dns one, a connection pool or a socket pool?</p>