Sub topic 18
Heap Pollution and @SafeVarargs
In the last chapter you saw that raw types cause unchecked warnings. This chapter explains what those warnings guard against. It also covers a common place where the problem appears: generic varargs.
What Heap Pollution Means
The heap is the memory area where Java stores objects. Heap pollution is when a variable of a generic type points to an object of the wrong type. For example, a List<String> might end up holding an Integer.
Because of type erasure, the program cannot notice this when it happens. The error appears later, often far from the line that caused it.
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 points to the same list
raw.add(42); // unchecked warning: heap pollution happens here
String s = strings.get(0); // ClassCastException happens here
System.out.println(s);
}
}The bad value goes in on one line. The crash comes on a different line.
Generic Varargs
A varargs parameter is one written with .... It lets a caller pass any number of arguments. Java collects those arguments into an array.
Java cannot create a real array of a generic type, such as List<String>[]. So it creates a plain List[] instead, and the compiler warns you: "possible heap pollution."
import java.util.List;
public class VarargsDanger {
static void dangerous(List<String>... lists) {
Object[] array = lists; // allowed: arrays are covariant
array[0] = List.of(42); // no error: at runtime it is just a List[]
String s = lists[0].get(0); // ClassCastException
System.out.println(s);
}
public static void main(String[] args) {
dangerous(List.of("a"), List.of("b"));
}
}Marking Safe Methods with @SafeVarargs
Most varargs methods only read from the array, and those methods are safe. The @SafeVarargs annotation tells the compiler, "I promise this method is safe," and the warning goes away.
import java.util.ArrayList;
import java.util.List;
public class SafeDemo {
@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;
}
public static void main(String[] args) {
List<String> names = listOf("Ada", "Linus");
System.out.println(names); // [Ada, Linus]
}
}A method is safe to annotate when it follows two rules:
- It never stores anything into the varargs array.
- It never lets the array escape, for example by returning it or saving it in a field.
You can use @SafeVarargs only on methods that cannot be overridden:
| Method kind | Allowed? |
|---|---|
| `static` method | Yes |
| `final` instance method | Yes |
| `private` instance method (Java 9+) | Yes |
| Constructor | Yes |
| Ordinary overridable instance method | No |
Exercise
A static method static <T> T[] toArray(T... items) { return items; } compiles with a heap pollution warning. Should you add @SafeVarargs to it? Why or why not?
Show answer
No. The method returns the varargs array, so the array escapes. The caller may treat a plain Object[] as a T[], which can cause a ClassCastException. That breaks the second safety rule.
Exercise
Why can't @SafeVarargs go on an ordinary public instance method?
Show answer
A subclass could override that method with an unsafe version. The promise would then be false, so Java allows the annotation only on static, final, or private methods and on constructors.