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.
A set of links that talks to DNS
The help-desk tool at Belgavi's Book Store collects the links mentioned in a case so the agent and the person handling it can see each one once. The first version kept them in a HashSet<java.net.URL>. Two symptoms followed. Adding links to a case sometimes took seconds when the network was slow. And a case that mentioned both https://shop.bookstore.example/orders/BK-1001 and https://help.bookstore.example/orders/BK-1001 showed only one link, because the set considered the two URLs equal.
Both come from one documented behaviour: java.net.URL.equals and URL.hashCode resolve host names. This guide measures that on JDK 23 with a resolver that counts lookups, explains when two different URLs compare equal, and shows the replacement.
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:
| Operation | Lookups | Result |
|---|---|---|
URI.create(...).toURL() | 0 | constructing does not resolve |
shop.equals(help), first comparison | 2 | true: different hosts, same address |
shop.equals(cdn) | 1 | false: cdn resolved for the first time |
shopUri.equals(helpUri) | 0 | false |
hashCode of shop and help, after the comparisons | 0 | equal, from the already resolved address |
Add 50 URLs on 50 different hosts to a HashSet<URL> | 50 | one lookup per new host |
contains for a host already seen | 0 | resolved addresses are cached |
Add 50 URIs on 50 new hosts to a HashSet<URI> | 0 | no resolution at all |
HashSet<URL> with shop and help | size 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.
Links that come from an agent
The help-desk tool's links are not typed by a careful engineer. Most of them are extracted by the agent from customer messages and tool results, which makes them untrusted input in two ways.
First, the agent controls the host names. With URL keys, every new host the model writes into a link triggers a DNS query from the help-desk service, from inside the service's network. That is a small information leak (the resolver sees which names the agent produced) and a way to make the service slow by feeding it names on a slow or unresponsive domain. With URI keys, collecting and deduplicating links touches no network at all, and resolution happens only when someone deliberately fetches a link, through the code path that already applies your outbound allowlist.
Second, the identity rule should be yours, not the resolver's. If the agent reports that two links are "the same order page", that should be because your canonicalisation function says so, for example the same scheme, lower-cased host, path and order id, and not because two hosts happened to share a load balancer address at that moment. Writing the rule down also gives you something to test: a table of link pairs that must and must not be merged.
Finding it in an existing codebase
- Search for
Set<URL>,Map<URL,,List<URL>followed bycontainsorindexOf, andURLfields in classes that are used as keys or compared withequals. - Compile with
-Xlint:deprecationto findnew 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") andDMI_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
URIis stricter about syntax. Strings thatnew URLaccepted, such as some with spaces or unescaped characters, makeURI.createthrow. 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/aandhttps://shop.bookstore.example:443/aare differentURIs. 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.