Practical technical guides / Core IT: Java (java.net)

java.net.URL equals and hashCode Resolve Host Names: Why a HashSet of URLs Does DNS Lookups

Measured on JDK 23: URL.equals resolved two hosts and called them equal because they share an address; a HashSet of 50 URLs did 50 lookups. Use URI for identity.

By Sandeep Belgavi · Published 2026-11-07

Measured on JDK 23: URL.equals resolved two hosts and called them equal because they share an address; a HashSet of 50 URLs did 50 lookups. Use URI for identity.

What the Javadoc says

The URL.equals documentation in Java SE 23 is explicit: "Two hosts are considered equivalent if both host names can be resolved into the same IP addresses; else if either host name can't be resolved, the host names must be equal without regard to case; or both host names equal to null. Since hosts comparison requires name resolution, this operation is a blocking operation." It adds a note that "the defined behavior for equals is known to be inconsistent with virtual hosting in HTTP". hashCode is "based upon all the URL components relevant for URL comparison", which includes the resolved host address.

The class documentation also says the URL constructors are deprecated, and that "developers are encouraged to use java.net.URI to parse or construct a URL", calling URI.toURL() only when an instance of URL is needed to open a connection.

Measuring it with a counting resolver

Since JDK 18 (JEP 418), applications can install their own host name resolver through the java.net.spi.InetAddressResolverProvider service interface. The companion example uses that to answer from a fixed table and count every forward lookup, so the measurement involves no real DNS. In the table, shop.bookstore.example and help.bookstore.example both resolve to 192.0.2.10, cdn.bookstore.example to 192.0.2.20, and branchN.bookstore.example to addresses in another documentation range.

public Stream<InetAddress> lookupByName(String host, LookupPolicy policy) throws UnknownHostException {
    LOOKUPS.incrementAndGet();
    byte[] a = TABLE.get(host.toLowerCase());
    if (a == null) throw new UnknownHostException(host);
    return Stream.of(InetAddress.getByAddress(host, a));
}

The provider is registered in META-INF/services/java.net.spi.InetAddressResolverProvider. Recorded on JDK 23.0.2:

OperationLookupsResult
URI.create(...).toURL()0constructing does not resolve
shop.equals(help), first comparison2true: different hosts, same address
shop.equals(cdn)1false: cdn resolved for the first time
shopUri.equals(helpUri)0false
hashCode of shop and help, after the comparisons0equal, from the already resolved address
Add 50 URLs on 50 different hosts to a HashSet<URL>50one lookup per new host
contains for a host already seen0resolved addresses are cached
Add 50 URIs on 50 new hosts to a HashSet<URI>0no resolution at all
HashSet<URL> with shop and helpsize 1: one link lost

Two unresolvable hosts that differ only in letter case (old-promo.bookstore.example and OLD-PROMO.bookstore.example) compare equal under both URL and URI. For URL that costs two failed lookups before the documented fallback to a case-insensitive name comparison; URI compares the names without any lookup. In total the probe made 55 lookups, every one of them attributed to a row above.

Why the cost is easy to miss

The JDK caches successful lookups, so in a warm process most equals calls hit the cache and look free. The cost appears on the first touch of each host, which in a link collector is every new link, and whenever the cache entry expires. With a slow or failing resolver each of those calls blocks the calling thread. In a request handler or an agent tool that is a latency spike that never shows up in tests run on a machine with fast DNS.

The equality problem is worse because it is silent. Hosts that share an address are common: virtual hosting, a CDN, a load balancer in front of several sites, a development machine where everything resolves to 127.0.0.1. Two distinct links collapse into one map key, and which one survives depends on insertion order. The result can also change over time, because the same two URLs may resolve to the same address today and different ones tomorrow, which breaks the equals and hashCode contract for anything stored in a hash table across that change.

Use URI for identity

import java.net.URI;
import java.util.LinkedHashSet;
import java.util.Set;

final class CaseLinks {
    private final Set<URI> links = new LinkedHashSet<>();

    void add(String text) {
        URI uri = URI.create(text).normalize();      // syntax only; no network
        if (!"https".equals(uri.getScheme())) throw new IllegalArgumentException("https links only");
        links.add(uri);
    }

    Set<URI> all() { return Set.copyOf(links); }
}

URI.equals compares the components as strings (with case-insensitive scheme and host, and the documented rules for escapes), never touching the network. normalize() removes . and .. path segments. If your idea of "the same link" is looser, for example ignoring a trailing slash or a default port, write that rule as an explicit canonicalisation function and test it, instead of relying on either class's equals.

Convert to URL only at the point where you open a connection, with uri.toURL(), and never keep URL objects as map keys, set members or cache keys.

Finding it in an existing codebase

  • Search for Set<URL>, Map<URL,, List<URL> followed by contains or indexOf, and URL fields in classes that are used as keys or compared with equals.
  • Compile with -Xlint:deprecation to find new URL(...) calls; the constructors have been deprecated since JDK 20 and are a good proxy for code that predates the advice.
  • SpotBugs has two checks for this: DMI_BLOCKING_METHODS_ON_URL ("The equals and hashCode methods of URL are blocking") and DMI_COLLECTION_OF_URLS ("Maps and sets of URLs can be performance hogs"). Enable them if you run SpotBugs.
  • In tests, install a resolver like the companion one that fails on any lookup, and run the code paths that handle links. Any failure is a hidden resolution.

Tradeoffs and failure modes of the replacement

  • URI is stricter about syntax. Strings that new URL accepted, such as some with spaces or unescaped characters, make URI.create throw. Parse at the boundary and reject or escape there, instead of deep inside business code.
  • String identity is not semantic identity. https://shop.bookstore.example/a and https://shop.bookstore.example:443/a are different URIs. Decide which differences matter and canonicalise explicitly.
  • Some APIs still want URL. That is fine at the call site; just do not store it.

Verification

The companion example's run.sh compiles the resolver and the probe, runs it with the resolver on the class path, and compares the output with the recorded JDK 23 results. To check your own service, run its link-handling tests with a resolver that throws on every lookup; if nothing fails, no URL comparison is resolving hosts.

Primary references and authorship

Original explanation and synthetic examples by Sandeep Belgavi. Companion code: Sandeep-BA/agent-decision-lab/examples/java/url_identity_probe. Views are my own and do not represent any employer, past or present.