Workbench / Volume 3 Companion: The Backend
V3·36
Generics
Companion to Volume 3, chapter 36: how generic types, bounds, variance, erasure and other languages' strategies connect; new angles (a typed key as a labelled jar, erasure as a shipping label removed at the dock, variance as who may put things into a box); what the chapter simplifies, measured on JDK 21 and the build's stage 37: a Map<Integer, byte[]> that accepted a malformed key and then wouldn't reopen, a compile error that reads like a proof once you know its words, a switch the compiler accepted without a case because of a type argument, and Netty's AttributeKey giving one key to two types; the theory behind parametric polymorphism; how Netty implements typed keys; four debugging drills; interview questions with how to approach each.
Understanding it better
Concept map
Chapter 36 has five parts: why generics exist (the problem, four implementation strategies), generic types and methods (classes, methods, inference), constraining type parameters (bounds, recursive bounds, associated types), variance (from first principles, wildcards and PECS, declaration-site variance) and erasure (what it removes, reifiable types, heap pollution), with monomorphisation, Go's generics and higher kinds for comparison.
The links worth remembering:
- Generics move checks from run time to compile time, and only there. Java erases type arguments, so everything generics promise is promised by the compiler. An unchecked cast or a raw type is a hole in that promise, and the failure appears later, somewhere else.
- Variance follows from who reads and who writes. A producer of
Tcan be covariant (? extends T), a consumer contravariant (? super T); something that does both must be invariant. - The implementation strategy decides the costs. Erasure (Java): one copy of the code, boxing, no run-time types. Monomorphisation (Rust, C++): fast specialised code, bigger binaries. Dictionaries and GC shapes (Go, Haskell): in between.
Explain it differently
1. A generic class is a jar with a label slot. Jar<T> is a jar; Jar<Lentils> is the same jar with a label. The kitchen staff (the compiler) refuse to pour rice into a jar labelled lentils.
2. A typed key is a labelled jar on a shared shelf. The shelf (a heterogeneous container) holds jars of different things. You don't ask for "jar 3"; you ask with the label Tag<Instant>, and what comes out is an Instant. Stage 37's extensions are this shelf.
3. Erasure is the label removed at the dock. Checks happen while the box is being packed (compile time). At the destination (run time), every box is just a box; if someone repacked one without a label (a raw type), nobody notices until it's opened.
4. Variance is about who may put things in. A box of apples can be lent as "a box of fruit" to someone who only takes fruit out (? extends Fruit). Lend it to someone who puts fruit in and you'll find a banana among the apples, so Java refuses.
5. Bounds are job requirements. <T extends Comparable<T>> says "any type, as long as it can be compared with its own kind": the method may then use compareTo, and callers must prove the requirement.
6. Monomorphisation is printing a menu per restaurant; erasure is one menu with blanks. Rust prints a specialised copy for each type (fast, more paper); Java prints one copy and fills in at the table (one copy, a little slower, and nobody at the table knows what was in the blank).
Gaps and misconceptions
What the chapter oversimplifies
All outputs are real, from OpenJDK 21.0.12 and the build's stage 37 (exp/37), unless stated.
1. An untyped container defers errors past the end of the program. The chapter's motivating examples fail with a ClassCastException when a value is read. TiffinBox's log extensions were a Map<Integer, byte[]>, a container so untyped that even the cast was hand-written. Reading the pricing tag as the customer compiled and ran:
customer = 1790;false;Welcome
And writing a malformed idempotency key as raw bytes succeeded, so the error moved past the program entirely, into the file:
appended, durable
reopen failed: java.lang.IllegalArgumentException: not a 128-bit hex key: 6f1c2a
The next start of the server would fail. With typed keys (Tag<IdempotencyKey>), the key is validated when it's constructed and the swap doesn't compile: incompatible types: IdempotencyKey cannot be converted to String. The chapter's point, "generics move errors to compile time", is about values; for data that is written down, the alternative is often an error at the next deploy.
2. Inference errors are proofs, once you can read them. Passing an int where a Tag<String> needs a String:
Infer.java:3: error: no suitable method found for of(Tag<String>,int)
method Extensions.<T>of(Tag<T>,T) is not applicable
(inference variable T has incompatible bounds
equality constraints: String
lower bounds: Integer)
method Extensions.<A,B>of(Tag<A>,A,Tag<B>,B) is not applicable
(cannot infer type-variable(s) A,B
(actual and formal argument lists differ in length))
Read it as the compiler's working: for each overload, it tried to find a T. From Tag<String> it got an equality constraint (T must be exactly String, because generics are invariant); from 42 (boxed) a lower bound (T must be a supertype of Integer). No type is both, so that overload fails; the other fails on arity. The fix is in the first overload's line: the second argument isn't a String. Long messages usually list every overload; find the one you meant and read its constraints.
3. Exhaustiveness looks at type arguments. The chapter (and stage 35) treat a sealed switch as needing every permitted subtype. Not quite:
sealed interface Value<T> {}
record Text(String s) implements Value<String> {}
record Count(int n) implements Value<Integer> {}
static String show(Value<String> v) { return switch (v) { case Text t -> t.s(); }; } // no Count case
dosa
It compiles and runs without a Count case, because a Count is a Value<Integer> and can never be a Value<String>. Generic sealed types can encode which cases are possible in which context; a raw Value parameter would bring the missing case back as a compile error.
4. Typed keys are only as safe as their names. A typed key is a name plus a type. If two pieces of code create keys with the same name and different types, the container has one slot and two beliefs about it. Netty's real AttributeKey:
same key object: true
newInstance("user"): 'user' is already in use
attr(userId).get() returned without complaint
it holds a String
Exception in thread "main" java.lang.ClassCastException: class java.lang.String cannot be cast to class java.lang.Integer
AttributeKey<String> and AttributeKey<Integer> made with valueOf("user") are the same object (the pool is keyed by name; the type argument is erased), so a value set through one is read through the other, and the failure is a ClassCastException at the reader. Netty offers newInstance, which refuses an existing name. Stage 37 has the same issue with tag numbers, which a test guards (everyExtensionTagHasItsOwnNumber), because the type system can't.
Common misconceptions
| Misconception | What's actually true | Where it's shown |
|---|---|---|
| "Generics check types at run time." | Only the compiler checks; at run time a Tag<String> is a Tag. |
the chapter's lab; Gaps 4 |
| "An unchecked warning is noise." | It marks the exact place the compile-time promise stops holding. | stage 37, step 4 |
| "Inference errors are unreadable." | They list each overload's constraints; read the one you meant. | Gaps 2 |
| "A sealed switch must list every subtype." | Not subtypes the type argument rules out. | Gaps 3 |
"List<Object> accepts any list." |
Generics are invariant; List<?> or List<? extends Object> does. |
Exercises P3 |
| "Typed keys make a container safe." | Only if names (or numbers) are unique per type. | Gaps 4 |
| "Generics cost nothing in Java." | No code cost, but boxing for primitives and a cast at each use. | Exercises P5 |
Theoretical gaps: the ideas behind the chapter
1. Parametric polymorphism and parametricity. A function <T> T id(T x) can't inspect T, so it can only return x (or loop, or throw). Wadler's "Theorems for free!" (1989) shows that a generic type alone implies laws: any <T> List<T> f(List<T>) commutes with map. Reflection and instanceof break parametricity, which is one reason erasure is less of a loss than it seems.
2. Subtyping and variance as a rule. If A <: B, then Producer<A> <: Producer<B> (covariant) and Consumer<B> <: Consumer<A> (contravariant); a type in both positions is invariant. Function types are contravariant in their arguments and covariant in their result; Java's arrays break this, which is why they need ArrayStoreException.
3. Bounded quantification. Cardelli and Wegner (1985) and System F<: give ∀T <: Bound. F-bounded polymorphism (Canning et al., 1989) is the recursive form, T extends Comparable<T>, used by Enum<E extends Enum<E>>.
4. Type-safe heterogeneous containers. Bloch's Effective Java, item 33: key the container on Class<T> and cast with Class.cast; limitations: no generic types as keys (no List<String>.class), one value per type. Typed keys (a tag object per field, as in stage 37 and Netty) remove both limits at the cost of unique names.
5. Higher-kinded types. Abstraction over type constructors (F<_>), as in Haskell's Functor; Java can't express <F<_>>, which is why there's no common map interface across Optional, Stream and CompletableFuture.
Applying it
Code walkthrough
Gaps 4 comes from how Netty, the networking library under many Java servers, implements typed keys for a channel's attributes. From netty/netty, branch 4.1, common/src/main/java/io/netty/util/.
The key: a name, a type, and an unchecked cast
public final class AttributeKey<T> extends AbstractConstant<AttributeKey<T>> {
private static final ConstantPool<AttributeKey<Object>> pool = new ConstantPool<AttributeKey<Object>>() {
@Override
protected AttributeKey<Object> newConstant(int id, String name) {
return new AttributeKey<Object>(id, name);
}
};
@SuppressWarnings("unchecked")
public static <T> AttributeKey<T> valueOf(String name) {
return (AttributeKey<T>) pool.valueOf(name);
}
@SuppressWarnings("unchecked")
public static <T> AttributeKey<T> newInstance(String name) {
return (AttributeKey<T>) pool.newInstance(name);
}
The pool stores AttributeKey<Object>s by name. valueOf casts the stored key to whatever T the caller asked for: after erasure that cast is to AttributeKey, so it always succeeds, and the @SuppressWarnings("unchecked") is the authors noting that the compiler can't check it. The safety argument is a convention: each name is used with one type.
The pool: get or create, or refuse
private T getOrCreate(String name) {
T constant = constants.get(name);
if (constant == null) {
final T tempConstant = newConstant(nextId(), name);
constant = constants.putIfAbsent(name, tempConstant);
if (constant == null) {
return tempConstant;
}
}
return constant;
}
private T createOrThrow(String name) {
T constant = constants.get(name);
if (constant == null) {
final T tempConstant = newConstant(nextId(), name);
constant = constants.putIfAbsent(name, tempConstant);
if (constant == null) {
return tempConstant;
}
}
throw new IllegalArgumentException(String.format("'%s' is already in use", name));
}
putIfAbsent on a ConcurrentMap makes creation thread-safe: two threads racing to create "user" both build a key, one wins, and both return the winner (getOrCreate) or the loser throws (createOrThrow). newInstance is the safe one for library code: a second library choosing the same name fails at startup instead of sharing a slot.
The map: one slot per key object
public <T> Attribute<T> attr(AttributeKey<T> key) {
ObjectUtil.checkNotNull(key, "key");
DefaultAttribute newAttribute = null;
for (;;) {
final DefaultAttribute[] attributes = this.attributes;
final int index = searchAttributeByKey(attributes, key);
final DefaultAttribute[] newAttributes;
if (index >= 0) {
final DefaultAttribute attribute = attributes[index];
assert attribute.key() == key;
if (!attribute.isRemoved()) {
return attribute;
}
The signature is the typed container: Attribute<T> attr(AttributeKey<T> key) ties the value's type to the key's. Inside, attributes are stored untyped (DefaultAttribute raw) in an array sorted by key id, searched by binary search and replaced copy-on-write with a compare-and-set loop, so reads take no lock. The assert attribute.key() == key is why two same-named keys collide: they are the same object.
Debugging drills
D1. A ClassCastException in a line with no cast
int count = cache.get(KEY); throws ClassCastException: class java.lang.Long cannot be cast to class java.lang.Integer. The line has no cast, and KEY is a Key<Integer>.
D2. Unchecked warnings everywhere after a library upgrade
After upgrading a JSON library, the build prints 40 unchecked warnings where code calls mapper.readValue(json, List.class), and one endpoint now returns LinkedHashMaps where it used to return Orders.
D3. An API that callers can't call
A method void addAll(List<Number> xs) is meant to accept any list of numbers. Callers with a List<Integer> get a compile error and copy their lists into new ArrayList<Number>(...) to call it.
D4. The switch that stopped compiling after "cleaning up" generics
A developer replaced Value<String> v with Value<?> v in a method "to make it more general", and a switch that had compiled for months now says it doesn't cover all possible input values.
Career-oriented
Interview prep
Mid-level 1: what erasure means
Question. "What is type erasure, and what can't you do in Java because of it?"
How to get there. What disappears, where checks happen, then the consequences.
Mid-level 2: ? extends and ? super
Question. "Write a method that copies all elements from one list to another, as general as possible."
How to get there. Who reads, who writes.
Senior 1: typed configuration or metadata
Question. "Design a way for many modules to attach typed metadata to a request without a central class that knows them all."
How to get there. A heterogeneous container, then name safety, then serialisation.
Senior 2: a generic API that callers hate
Question. "Callers of our generic library constantly write explicit type arguments and casts. How do you improve it?"
How to get there. Inference, wildcards, and how many type parameters are visible.
Staff 1: Java generics against other languages
Question. "We're choosing between Java, Go and Rust for a new data-processing service. How do their generics affect the decision?"
How to get there. Performance model, expressiveness, team cost.
Staff 2: removing raw types from a large codebase
Question. "Our 2-million-line codebase has 9,000 unchecked warnings. Do we fix them, and how?"
How to get there. Risk, prioritisation, prevention.