skip to content

Blocking Sockets & URLs

java.net is the JDK's blocking network API: Socket and ServerSocket, URI and URL, and InetAddress for name lookup. Interviewers ask it to see whether you know what a thread per connection costs and why URL.equals is a trap.

part ofJavaread it →
on this pageshow

questions

4

What are java.net.URI and java.net.URL, how do they differ, and why should you keep a URI rather than a URL?

level: juniorimportance: should knowfreq 45%

answer

  1. identifier versus locator
  2. text-only equality
  3. a handler per protocol
  4. equals that resolves host names
  5. constructors deprecated, use toURL()

basics

~20 s

URI is a parsed identifier compared by its text alone; URL is a locator tied to a protocol handler that can open a connection. URL.equals and hashCode resolve host names, so keep URIs and convert with uri.toURL() only to connect.

solid answer

~50 s

A `URI` is an RFC 2396 reference parsed without regard to its scheme: it can be relative or opaque (`urn:isbn:...`), no host lookup happens, and `equals`/`hashCode` work on its characters, with scheme and host compared without regard to case. A `URL` must be absolute and gets a `URLStreamHandler` for its protocol when it is created (an unknown scheme throws `MalformedURLException`), which is what lets it `openConnection()`. The trap: `URL.equals` treats two hosts as equal when they resolve to the same IP address and `hashCode` uses that address, and both are documented as blocking operations. A `HashSet<URL>` therefore resolves names and merges sites that share an IP. Store and compare `URI`s. Since JDK 20 every `URL` constructor is deprecated: build a `URI` with `new URI(...)` or `URI.create(...)` and call `toURL()`, or `URL.of(uri, handler)` for a custom handler.

code

java · 21 lines
java
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.HashSet;
import java.util.Set;

public class UriFirst {
    public static void main(String[] args) throws URISyntaxException, MalformedURLException {
        URI uri = new URI("https", "example.com", "/docs/a b", "q=1", null);
        System.out.println(uri); // https://example.com/docs/a%20b?q=1

        Set<URI> seen = new HashSet<>(); // URI equality works on the text: no name lookup
        seen.add(uri);
        seen.add(URI.create("https://EXAMPLE.com/docs/a%20b?q=1"));
        System.out.println(seen.size()); // 1: scheme and host compare without regard to case

        URL url = uri.toURL(); // convert only where a connection is opened
        System.out.println(url.getProtocol()); // https
    }
}

go deeper

for a junior

Recall that a URI identifies and a URL locates, and that you build a URL from a URI with toURL() because the URL constructors are deprecated.

for a middle

Explain why URL.equals and hashCode resolve host names, what that does to a HashSet of URLs, and how URI equality differs from it.

for a senior

Show that you keep URIs in data structures and APIs, validate input with the URI constructor and parseServerAuthority(), and convert to URL only where a connection opens.

for a principal

Set the codebase rule: URIs at boundaries and in collections, a review or lint check against URL keys and deprecated constructors, and a plan for legacy URL-based APIs.

## Identifier versus locator The `URI` Javadoc puts it plainly: a URI is a uniform resource **identifier**, a URL a uniform resource **locator**, so every URL is a URI but not every URI is a URL. A name such as `urn:isbn:0451450523` identifies a book without saying how to fetch it. Java models the two with different classes, and their behaviour differs more than the names suggest. ## `java.net.URI`: a structured string - It is parsed by the generic syntax, without regard to the scheme. No host lookup happens and no protocol handler is created. - It may be absolute or relative, hierarchical or **opaque** (`urn:isbn:...`). - `new URI(String)` throws the checked `URISyntaxException`; `URI.create(String)` wraps that in an `IllegalArgumentException` and is meant for strings known to be valid, such as constants. - The multi-argument constructors quote illegal characters for you: `new URI("https", "example.com", "/a b", null)` produces `https://example.com/a%20b`. - `resolve()`, `relativize()` and `normalize()` work on the text alone. - **Equality and hashing use only the characters.** The scheme and host compare without regard to case, as do the hex digits of escapes, but `%7E` and `~` stay different, and `/a/../b` equals `/b` only after `normalize()`. ## `java.net.URL`: a locator with a handler - A URL must be absolute. A `URLStreamHandler` for its protocol is chosen when the URL is created, and a URL cannot exist for a protocol with no handler: `URI.create("urn:isbn:0451450523").toURL()` throws `MalformedURLException`. - That handler is what lets a URL `openConnection()` and `openStream()`. - `URL` does no escaping of its own. The deprecated constructors accept `http://example.com/a b`, and `toURI()` on such a URL then throws `URISyntaxException`. ## The trap in `URL.equals` and `hashCode` Two URLs are equal when they have the same protocol, port, file and fragment and **equivalent hosts**, and two hosts are equivalent when both names resolve to the same IP addresses. Only when either name cannot be resolved are the names compared, without regard to case. - Both methods are documented as **blocking operations**, because they may resolve a host name. - A `HashSet<URL>`, or a `HashMap` keyed by `URL`, therefore resolves names, and it merges different sites hosted on one IP. The Javadoc itself says that `equals` is inconsistent with virtual hosting in HTTP. - The answer depends on the network at the moment you ask: a machine that cannot resolve the names compares them as text, one that can compares addresses. `hashCode()` is computed once and then cached in the URL object. Store, compare and key by `URI`, and convert to `URL` at the point where a connection is opened. ## Building a URL since JDK 20 | Deprecated since JDK 20 | Use instead | |---|---| | the four `URL` constructors without a handler | a `URI` from `new URI(...)`, `URI.create(...)` or `resolve(...)`, then `toURL()` | | the two constructors that take a `URLStreamHandler` | `URL.of(uri, handler)` | - The constructors are deprecated, not marked for removal. The `URL` Javadoc's advice is to parse or build with `URI`, optionally call `parseServerAuthority()` to check the authority, then call `toURL()`. - `URI.toURL()` throws `IllegalArgumentException` for a relative URI and `MalformedURLException` when no handler exists for the scheme. - `URL.of(URI, URLStreamHandler)`, added in JDK 20, is only needed for a custom handler. ## Taking a URL from untrusted input 1. Parse with `new URI(input)` and treat `URISyntaxException` as bad input. 2. Require what you expect: `isAbsolute()`, a scheme from your allow-list via `getScheme()`, and a non-null `getHost()`. 3. Call `parseServerAuthority()`, which parses the authority again as user information, host and port and throws `URISyntaxException` when it cannot. The generic syntax alone accepts some malformed server authorities, such as `//foo:bar`, as registry-based ones. 4. Only then call `toURL()`, at the place where the connection opens. Steps 2 and 3 can swap; step 1 must come first and step 4 last. ## Practical rules - Key sets and maps by `URI`, never by `URL`. - The JDK's HTTP client takes a `URI` (covered with that client). - `URLEncoder` does HTML form encoding, which the `URL` Javadoc says is not the URI escaping scheme; let `URI`'s multi-argument constructors quote components instead. - For files, `Path.of(URI)` and `Path.toUri()` convert in both directions.

  • Why might two URL objects for different websites compare equal?
    `URL.equals` compares hosts by resolved IP address. Two sites served from the same address, which is ordinary with virtual hosting, resolve alike, so their URLs are equal when protocol, port, file and fragment match; the Javadoc notes this inconsistency with virtual hosting. `URI.equals` compares the host text and keeps them apart.
  • What is the difference between new URI(String) and URI.create(String)?
    Both parse the same way. The constructor throws the checked `URISyntaxException`, which suits input from users or files. `URI.create` catches that and throws an unchecked `IllegalArgumentException`; the Javadoc intends it for strings known to be valid, such as URI constants in a program.
  • Do URI.equals() and hashCode() treat http://example.com/a/../b and http://example.com/b as the same?
    No. URI equality is textual and does not normalise, so the two differ until you call `normalize()` on both. Likewise `%7E` and `~` stay different, although the hex digits inside escapes compare without regard to case.

URL.equals is a receptionist who decides two letters are for the same company because both addresses lead to the same office building; URI.equals reads the company names on the envelopes. With virtual hosting, many companies share one building.

  • URL.equals compares the two URL strings character by character.
  • Every URI can be turned into a URL with toURL().
  • new URL(String) is still the recommended way to build a URL.
  • URLEncoder.encode gives a correctly escaped URI path.
  • A URI must always have a scheme; relative URIs are invalid.

java.net.URI
Java 1.4
java.net.URL
Java 1.0
URL.of(URI, URLStreamHandler)
Java 20

Assumes JDK 27; URL's constructors are deprecated since JDK 20, when URL.of(URI, URLStreamHandler) was added, and JDK 25 behaves the same.

context

open as a page

How do Java's Socket and ServerSocket handle blocking TCP, from accept to half-close and timeouts, and why did that lead to thread-per-connection?

level: middleimportance: should knowfreq 45%

basics

~20 s

ServerSocket.accept() blocks until a client connects and returns a Socket with one input and one output stream. Its reads block too unless setSoTimeout sets a limit, and one thread cannot wait on several Sockets, so each connection got its own thread.

open as a page

How does a blocking java.net.Socket differ from a SocketChannel, and when does each fit now that virtual threads exist?

level: middleimportance: should knowfreq 40%

basics

~20 s

A Socket moves bytes through blocking streams; a SocketChannel moves ByteBuffers, can run non-blocking under a Selector, and is closed by an interrupt on any thread. On virtual threads both block cheaply, so pick channels for buffers, selectors or Unix-domain sockets.

open as a page

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%

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.

open as a page