Sub topic 18
Heap Pollution and @SafeVarargs
This chapter covers the last pitfall caused by type erasure. You will learn what heap pollution is, why methods with generic varargs can cause it, and when you can mark such a method with @SafeVarargs to tell the compiler it is safe.
What Heap Pollution Means
The heap is the area of memory where Java keeps objects. Heap pollution is a situation where a variable of a generic type, such as List<String>, points to an object that does not hold the type the variable promises. For example, a List<String> variable might point to a list that contains an Integer.
The compiler normally prevents this. It can only happen when the compiler loses track of the real type. That happens in two main ways:
- You use a raw type, which is a generic type written without its type argument, such as
Listinstead ofList<String>. - You use an unchecked cast, which is a cast the JVM cannot check at runtime because type arguments are erased.
In both cases the compiler gives an unchecked warning. A warning is a message that does not stop compilation but points out risky code.
Here is heap pollution caused by a raw type:
import java.util.ArrayList;
import java.util.List;
public class PollutionDemo {
public static void main(String[] args) {
List<String> strings = new ArrayList<>();
List raw = strings; // raw type: compiler stops checking
raw.add(42); // unchecked warning; heap is now polluted
System.out.println(strings.size()); // 1, no error yet
String s = strings.get(0); // ClassCastException here
}
}The bad value goes in at one line, but the program fails at a different line. The failure happens when the code reads the value and Java inserts a hidden cast to String. In a real program these two lines could be in different files, which makes the bug hard to find.
Varargs: A Quick Review
Varargs, short for "variable arguments", lets a method take any number of arguments of one type. You write three dots after the type:
public class VarargsReview {
static int sum(int... numbers) {
int total = 0;
for (int n : numbers) {
total += n;
}
return total;
}
public static void main(String[] args) {
System.out.println(sum(1, 2, 3)); // 6
}
}Behind the scenes, Java packs the arguments into an array. The parameter int... numbers is really an int[].
Why Generic Varargs Are a Problem
Now combine varargs with generics. Suppose a method takes T... items or List<String>... lists. Java must build an array of T or of List<String>. But an earlier chapter showed that you cannot create generic arrays, because erasure removes the type argument and the array cannot check what goes into it.
For varargs, Java makes an exception and creates the array anyway. Because of erasure, a List<String>[] is really just a List[] at runtime. So the compiler warns you. If you compile with javac -Xlint:unchecked, you see something like:
warning: [unchecked] Possible heap pollution from parameterized vararg type List<String>Here is how that array can be abused:
import java.util.List;
public class DangerousVarargs {
static void dangerous(List<String>... lists) {
Object[] array = lists; // arrays are covariant, so this compiles
array[0] = List.of(42); // the array cannot detect the wrong List type
String s = lists[0].get(0); // ClassCastException
}
public static void main(String[] args) {
dangerous(List.of("a"), List.of("b"));
}
}The method stored a List<Integer> into an array that was supposed to hold only List<String>. The JVM only checks that the element is a List, so the store succeeds. The program crashes on the next line.
The Hidden Danger: Letting the Array Escape
A method can also cause trouble without storing anything. It only has to hand its varargs array to code that trusts its type. This example looks harmless:
public class EscapingArray {
static <T> T[] toArray(T... args) {
return args; // the varargs array escapes
}
static <T> T[] pickTwo(T a, T b, T c) {
return toArray(a, b);
}
public static void main(String[] args) {
String[] pair = pickTwo("x", "y", "z"); // ClassCastException
System.out.println(pair.length);
}
}Inside pickTwo, T is erased to Object. So when pickTwo calls toArray(a, b), Java creates an Object[], not a String[]. That Object[] is returned to main, which tries to treat it as a String[]. The cast fails, even though every value really is a String.
@SafeVarargs: Promising the Compiler
Many generic varargs methods are perfectly safe. List.of(...) and Arrays.asList(...) both take T... and never misuse the array. For methods like these, Java offers the @SafeVarargs annotation. An annotation is a label starting with @ that gives extra information to the compiler.
@SafeVarargs is a promise from you, the author: "This method does not misuse its varargs array." The compiler then stops warning about heap pollution, both in the method and at every place it is called.
import java.util.ArrayList;
import java.util.List;
public class SafeListBuilder {
@SafeVarargs
static <T> List<T> listOf(T... items) {
List<T> result = new ArrayList<>();
for (T item : items) {
result.add(item); // only reads from the array
}
return result; // returns a new list, not the array
}
public static void main(String[] args) {
List<String> names = listOf("Ada", "Linus", "Grace");
System.out.println(names); // [Ada, Linus, Grace]
}
}The method only reads from items and returns a new list, so the promise is true.
When a Varargs Method Is Safe
A generic varargs method is safe if both of these are true:
- It does not store anything into the varargs array.
- It does not let the array escape. It does not return the array or pass it to code you do not trust. Passing it to another
@SafeVarargsmethod, or passing its contents to a normal method, is fine.
Where You Can Use @SafeVarargs
The annotation is only allowed on methods that cannot be overridden, because a subclass could override the method with an unsafe version.
| Kind of method | @SafeVarargs allowed? |
|---|---|
| `static` method | Yes |
| `final` instance method | Yes |
| `private` instance method | Yes (Java 9 and later) |
| Constructor | Yes |
| Ordinary instance method that can be overridden | No, compile error |
| Method that is not varargs | No, compile error |
Alternatives to Generic Varargs
Sometimes it is simpler to avoid the problem. Instead of T... items, a method can take a List<T>:
import java.util.List;
public class ListParameter {
static <T> T firstOf(List<T> items) {
return items.get(0);
}
public static void main(String[] args) {
System.out.println(firstOf(List.of("a", "b"))); // a
}
}The caller writes List.of(...), which is already marked @SafeVarargs. No generic array is involved, so there is no warning. The trade-off is that the call is a little longer to write.
Summary
- Heap pollution means a generic variable points to an object of the wrong type. It shows up later as a
ClassCastException. - Raw types, unchecked casts, and generic varargs can all cause it. The compiler warns about each one.
- A generic varargs method is safe if it never writes to its array and never lets the array escape.
- Use
@SafeVarargsonly on safe methods that arestatic,final,private, or constructors.
Exercise
A method is declared as @SafeVarargs static <T> T[] wrap(T... items) { return items; }. Is the annotation correct? Explain.
Show answer
No. The method returns the varargs array, so the array escapes. If wrap is called from another generic method where T is erased, the array will be an Object[], and a caller expecting something like String[] will get a ClassCastException. The annotation hides the warning but does not remove the danger.
Exercise
Why does the compiler reject @SafeVarargs on an ordinary public instance method that is not final?
Show answer
A subclass could override that method and misuse the varargs array. The annotation is only a promise about one specific method body, so Java allows it only on methods that cannot be overridden: static, final, private methods, and constructors.
Exercise
In the PollutionDemo program, the line raw.add(42) runs without error. On which line does the program actually fail, and why there?
Show answer
It fails on String s = strings.get(0). Adding to a raw list performs no type check. When the value is read through the List<String> variable, Java inserts a hidden cast to String, and that cast fails because the value is an Integer.