Tuesday 25 October 2011

Heap pollution

What is it?

Java Language Specification, Third Edition
§4.12.2.1 Heap Pollution
It is possible that a variable of a parameterized type refers to an object that is not of that parameterized type. This situation is known as heap pollution. This situation can only occur if the program performed some operation that would give rise to an unchecked warning at compile-time.

Here is an example:

List l = new ArrayList();
List l1 = l;
l.add("one");
Integer i = l1.get(0);

In java 7 the following additions help to deal with Heap Pollution:

  • A new mandatory compiler warning is generated on declaration sites of problematic varargs methods that are able to induce contributory heap pollution.
  • The ability to suppress those mandatory warnings at a declaration site using an @SuppressWarnings("varargs") annotation. The warnings may also be suppressing using the -Xlint:-varargs option to the compiler.
  • If the @SuppressWarnings("varargs") annotation is used on a problematic varargs method declaration, the unchecked warnings at call sites of that method are also suppressed.

No comments: