Skip to main content
查利博客

Java Heap Pollution

According to the Wikipedia, Heap Pollution is defined as follows:

In the Java programming language, heap pollution is a situation that arises when a variable of a parameterized type refers to an object that is not of that parameterized type.

First, you may wonder what are parameterized types? They are literally something like List<String> or Set<Integer>. See following examples for more details.

Parameterized Type Example #

import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Collection;
import java.util.List;
import java.util.Set;

public class ParameterizedTypesExample<T> {
  /* Parameterized Types */
  public Collection<String> collectionOfString;
  public Set<Integer> setOfInteger;
  public Class<?> clazz;
  public List<T> listOfT;
  public List<? extends Number> listOfNumber;

  /* Non Parameterized Types */
  public String string;
  public T[] arrayOfT;
  public String[] arrayOfString;

  public static void main(String[] args) {
    Field[] fields = ParameterizedTypesExample.class.getFields();
    Type type = null;
    for (Field field : fields) {
      type = field.getGenericType();
      if (type instanceof ParameterizedType) {
        ParameterizedType parameterizedType = (ParameterizedType) type;
        System.out.println("Parameterized Types " + parameterizedType);
      } else {
        System.out.println("Non Parameterized Types " + type.getTypeName());
      }
    }
  }
}

Output:

Parameterized Types java.util.Collection<java.lang.String>
Parameterized Types java.util.Set<java.lang.Integer>
Parameterized Types java.lang.Class<?>
Parameterized Types java.util.List<T>
Parameterized Types java.util.List<? extends java.lang.Number>
Non Parameterized Types java.lang.String
Non Parameterized Types T[]
Non Parameterized Types java.lang.String[]

Heap Pollution Example #

Simply put, heap pollution occurs when an instance of a class does not match the generic declaration. This results in java.lang.ClassCastException at runtime.

import java.util.HashSet;
import java.util.Set;

public class HeapPollutionExample {
  public static void main(String[] args) {
    Set<String> setOfString = new HashSet<>();
    setOfString.add("caizhenhua");
    Set<Integer> setOfInteger = (Set<Integer>) (Object) setOfString;
    for (Integer integer : setOfInteger) {
    }
  }
}

Output:

Exception in thread "main" java.lang.ClassCastException: class java.lang.String cannot be cast to class java.lang.Integer (java.lang.String and java.lang.Integer are in module java.base of loader 'bootstrap')
	at com.caizhenhua.javase.generics.HeapPollutionExample.main(HeapPollutionExample.java:11)

IDE like Eclipse or IDEA normally will detect heap pullution situation at the compile-time and throw unchecked cast warning message like below.

Type safety: Unchecked cast from Object to Set<Integer>	HeapPollutionExample.java