java‎ > ‎

What is heap pollution?

posted Jun 20, 2010, 7:59 PM by Kuwon Kang

Java Generic type중 Heap 오염이란 내용이 있어 올려 본다.

What is heap pollution?

A situation where a variable of a parameterized type refers to an object that is not of that parameterized type.

It can happen that a variable of a parameterized type such as List<String> refers to an object that is not of that

parameterized type.

Example (of heap pollution):

List ln = new ArrayList<Number>();

List<String> ls =ln; // unchecked warning

String s = ls.get(0);// ClassCastException

After the assignment of the reference variable ln to the reference variable ls, the List<String> variable will point

to a List<Number> object. Such a situation is called heap pollution and is usually indicated by an unchecked warning.

A polluted heap is likely to lead to an unexpected ClassCastException at runtime. In the example above, it will lead

to a ClassCastException, when a object is retrieved from the List<String> and assigned to a String variable, because the

object is a Number, not a String.

LINK TO THIS Technicalities.FAQ050

REFERENCES What is an "unchecked" warning?

When does heap pollution occur?

As a result of mixing raw and parameterized type, unwise casting, and separate compilation.

Heap pollution occurs in three situations:

● mixing raw types and parameterized types

● performing unchecked casts

● separate compilation of translation units

With the exception of separate compilation, the compiler will always issue an unchecked warning to draw your attention to

the potential heap pollution. If you co-compile your code without warnings then no heap pollution can ever occur.

Raw Types

Heap pollution can occur when raw types and parameterized types are mixed and a raw type variable is assigned to

a parameterized type variable. Note, that heap pollution does not necessarily occur, even if the compiler issues an

unchecked warning.

Example (of mixing raw and parameterized types):

List ln = new ArrayList<Number>();

List ls = new LinkedList<String>();

List<String> list;

list = ln; // unchecked warning + heap pollution

list = ls;// unchecked warning + NO heap pollution

The first assignment leads to heap pollution, because the List<String> variable would then point to a List<Number>.

The second assignment does not result in heap pollution, because the raw type variable on the right-hand side of the

assignment refers to a List<String>, which matches the parameterized type on the left-hand side of the assignment.

Mixing raw and parameterized types should be avoided, if possible. It cannot be avoided when non-generic legacy code

is combined with modern generic code. But otherwise, the mix is bad programming style.

Comments