skip to content

What does java.net.InetAddress do to resolve a name, what do its caches hold, and why can a long-lived JVM keep a stale address?

level: seniorimportance: should knowfreq 35%

answer

  1. literal, cache, then resolver
  2. a fixed TTL, not the record's
  3. security properties, read once
  4. held addresses never refresh
  5. open connections outlive DNS

basics

~20 s

InetAddress.getByName asks the system-wide resolver, by default the OS's, and caches the answer per host name: successes for networkaddress.cache.ttl, 30 s by default, failures for 10 s. Stale addresses also outlive the cache in held InetSocketAddress objects and open connections.

solid answer

~40 s

`getByName`/`getAllByName` return a literal IP without any lookup. For a name they consult a process-wide cache, then the system-wide `InetAddressResolver`: the OS resolver by default, replaceable through the SPI added in JDK 18. Successful results stay for the security property `networkaddress.cache.ttl` (30 seconds by default in the JDK, `-1` for forever), failures for `networkaddress.cache.negative.ttl` (10 seconds), and `networkaddress.cache.stale.ttl` can keep serving an expired entry while refreshes fail. The cache applies that fixed policy, not each DNS record's TTL. Staleness usually outlives the cache, though: an `InetAddress` is a fixed value, `new InetSocketAddress(host, port)` resolves once in its constructor, and an open connection stays with the IP it reached, so long-lived clients and pools keep using the old host until they re-resolve or reconnect.

code

java · 25 lines
java
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.security.Security;

public class FreshAddress {
    public static void main(String[] args) throws IOException {
        // A security property, read once: set it before the first name lookup.
        Security.setProperty("networkaddress.cache.ttl", "10");

        String host = args.length > 0 ? args[0] : "localhost";
        for (InetAddress address : InetAddress.getAllByName(host)) {
            System.out.println(address);
        }
    }

    // Keep the host name, not an InetSocketAddress built at startup:
    // each reconnect resolves again, subject to the cache TTL above.
    static Socket connect(String host, int port) throws IOException {
        Socket socket = new Socket();
        socket.connect(new InetSocketAddress(host, port), 2_000); // closes the socket on failure
        return socket;
    }
}

go deeper

for a junior

Recall that InetAddress turns host names into IP addresses, that getByName returns one address for the name (the first, in the JDK), and that the JVM caches lookups for a while.

for a middle

Explain the three cache properties, the JDK defaults of 30 and 10 seconds, and why they are security properties rather than system properties.

for a senior

Diagnose stale-address incidents: held InetSocketAddress objects, long-lived pooled connections and cache settings, and make every reconnect resolve the name again.

for a principal

Set the policy for DNS-driven failover across services: cache TTLs, connection lifetimes, whether stale answers are acceptable during outages, and when a custom resolver is justified.

## What `InetAddress` is `java.net.InetAddress` (JDK 1.0) represents an IP address, with `Inet4Address` and `Inet6Address` as its subclasses, optionally together with the host name it came from. Its static factories turn names into addresses: - `getAllByName(host)` returns every address for a name. `getByName(host)` is specified only to return an address for the name; in the JDK it is the first of them. - For a literal such as `"192.0.2.1"` only the format is checked; no lookup happens. - A `null` or empty host gives a loopback address. ## How a name is resolved 1. For a host that is not a literal address, `getAllByName` evicts expired entries and then looks in a process-wide cache keyed by host name. 2. On a miss, one thread per name asks the **system-wide resolver**, while other callers for that name wait on a lock inside the private `NameServiceAddresses` class. By default the resolver is the built-in one, which uses the machine's configuration and naming services such as DNS; since JDK 18 an `InetAddressResolverProvider` found through `ServiceLoader` can replace it (JEP 418). 3. The result, addresses or a failure, goes into the cache for as long as the cache policy allows, and the waiting callers read it from there. The cache sits in front of every resolver, a custom one included. The lookup methods take no timeout, and the built-in resolver blocks in an operating-system call; JEP 418 names that blocking as one motivation for the SPI. On a virtual thread the JDK wraps that call in its internal `jdk.internal.misc.Blocker`, so the scheduler's pool can expand while the lookup blocks. ## The three cache settings | Security property | Meaning | JDK default | |---|---|---| | `networkaddress.cache.ttl` | seconds to keep a successful lookup; `-1` forever, `0` never | 30 (the Javadoc calls it implementation-specific) | | `networkaddress.cache.negative.ttl` | seconds to keep a failed lookup; `-1` forever, `0` never | 10 | | `networkaddress.cache.stale.ttl` | seconds an expired entry may still be used when a refresh fails; if larger than the TTL, the TTL becomes a refresh interval | 0, meaning off | - These are **security** properties. Set them in the `java.security` file, in a file passed with `-Djava.security.properties=<file>`, or with `Security.setProperty()` before the first lookup. They are read once, when the private `InetAddressCachePolicy` class initialises. - `-Dnetworkaddress.cache.ttl=5` does nothing. The system properties `sun.net.inetaddr.ttl`, `sun.net.inetaddr.negative.ttl` and `sun.net.inetaddr.stale.ttl` are read only as fallbacks when the security property is unset; the shipped `java.security` sets `networkaddress.cache.negative.ttl=10`, so the negative fallback has no effect until that line is removed. - The cache applies this fixed policy, not each DNS record's TTL: neither the built-in resolver nor the resolver SPI hands a record TTL back to `InetAddress`. - The `java.security` file warns that setting the positive TTL to anything other than the default can have serious security implications, and not to do it unless you are sure you are not exposed to DNS spoofing. ## Why a long-lived JVM keeps a stale address - **The cache window.** Within the TTL every lookup returns the old answer, a failure is served for 10 seconds, and a positive stale TTL deliberately keeps serving an expired answer while refreshes fail. - **Values you hold.** An `InetAddress` never changes. `new InetSocketAddress(host, port)` resolves the name once, in its constructor, so a client that builds it at startup and reuses it for every reconnect never resolves again, whatever the TTL. - **Open connections.** An established connection stays with the IP it reached. A pool that keeps connections open indefinitely keeps using the old server long after DNS has moved. - **The first address only.** In the JDK, `new Socket(host, port)` resolves through `getByName()` and connects to that one address, with no fallback to the others. - **Below the JVM.** The built-in resolver asks the operating system, whose own caches the JVM cannot see or flush. ## Diagnosing and fixing - Check the effective settings. On JDK 27, `jcmd <pid> VM.security_properties` prints a running JVM's security properties; JDK 25 does not have that command. - Keep the host name and build a new `InetSocketAddress` for each connection attempt, so every reconnect goes through the cache and its TTL. - Give pooled connections a maximum lifetime, so they reconnect, and resolve again, on a schedule. - Remember that each JVM process has its own cache: restarting one instance refreshes only that instance's view of DNS. - When you need to know what the JVM itself currently resolves, rather than what a shell on the same machine sees, log `InetAddress.getAllByName(host)` from inside the process. - Turn on `networkaddress.cache.stale.ttl` only where using a possibly outdated address beats failing during a DNS outage.

  • Why does passing -Dnetworkaddress.cache.ttl=5 on the command line appear to do nothing?
    Because `networkaddress.cache.ttl` is a security property, not a system property. Set it in the `java.security` file, in a file passed with `-Djava.security.properties`, or with `Security.setProperty()` before the first lookup; the system-property fallback is `-Dsun.net.inetaddr.ttl`. All of them are read once, when the cache policy class initialises.
  • After a DNS failover, some clients keep reaching the old IP for hours, far beyond 30 seconds. Where do you look?
    Not at the default cache: 30 seconds cannot explain hours. Look for an `InetSocketAddress` or `InetAddress` built once and reused, pooled connections with no maximum lifetime, and a TTL of `-1` in `java.security`, or a large stale TTL on clients whose lookups are failing, since a stale entry is served only while refreshes fail. On JDK 27, `jcmd <pid> VM.security_properties` shows the effective values.
  • What does networkaddress.cache.stale.ttl buy you, and what does it cost?
    If a refresh fails after the TTL expires, the cache keeps serving the old address for up to that many seconds instead of failing; when it is larger than the TTL, the TTL becomes the refresh interval. You gain resilience to a DNS outage and pay with the risk of connecting to an address that is no longer right. It is off by default.

  • The JVM caches each name for the TTL in its DNS record.
  • Passing -Dnetworkaddress.cache.ttl as a system property changes the cache.
  • Lowering the cache TTL makes an existing InetSocketAddress pick up a new IP.
  • new Socket(host, port) tries every address the name resolves to until one connects.
  • Failed lookups are never cached, so each retry queries DNS again.

java.net.InetAddress
Java 1.0
InetAddress resolver SPI (InetAddressResolver)
Java 18
networkaddress.cache.stale.ttl
Java 21

Assumes JDK 27; the cache properties and defaults are the same at JDK 25, the resolver SPI dates from JDK 18, networkaddress.cache.stale.ttl from JDK 21, and jcmd VM.security_properties is new in JDK 27.

context