Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Parasoft Jtest 2021.1

Heap pollution occurs when a variable of a parameterized type references an object that is not of that parameterized type. (For more information on heap pollution, see The Java Language Specification (JLS), §4.12.2, "Variables of Reference Type" [JLS 2015].)

Mixing generically typed code with raw typed code is one common source of heap pollution. Generic types were unavailable prior to Java 5, so popular interfaces such as the Java Collection Framework relied on raw types. Mixing generically typed code with raw typed code allowed developers to preserve compatibility between nongeneric legacy code and newer generic code but also gave rise to heap pollution. Heap pollution can occur if the program performs some operation involving a raw type that would give rise to a compile-time unchecked warning.

When generic and nongeneric types are used together correctly, these warnings can be ignored; at other times, these warnings can denote potentially unsafe operations. Mixing generic and raw types is allowed provided that heap pollution does not occur. For example, consider the following code snippet.

Code Block
List list

Generically typed code can be freely used with raw types when attempting to preserve compatibility between non-generic legacy code and newer generic code. Using raw types with generic code causes most Java compilers to issue "unchecked" warnings but still compile the code. When generic and non-generic types are used together correctly, these warnings can be ignored; at other times, these warnings can denote potentially unsafe operations.

Wiki Markup
According to the _Java Language Specification_ \[[JLS 2005|AA. Bibliography#JLS 05]\], [§4.8 "Raw Types,"|http://java.sun.com/docs/books/jls/third_edition/html/typesValues.html#4.8]

The use of raw types is allowed only as a concession to compatibility of legacy code. The use of raw types in code written after the introduction of genericity into the Java programming language is strongly discouraged. It is possible that future versions of the Java programming language will disallow the use of raw types.

If a parameterized type tries to access an object that is not of the parameterized type, heap pollution occurs. For instance, consider the code snippet below.

Code Block

List l = new ArrayList();
List<String> ls = llist; // Produces unchecked warning

Wiki Markup
It is insufficient to rely on unchecked warnings alone to detect violations of this rule. According to the JLS \[[JLS 2005|AA. Bibliography#JLS 05]\], [&#xA7;4.12.2.1, "Heap Pollution," |http://java.sun.com/docs/books/jls/third_edition/html/typesValues.html#111088]

Wiki Markup
Note that this does not imply that heap pollution only occurs if an unchecked warning actually occurred. It is possible to run a program where some of the binaries were compiled by a compiler for an older version of the Java programming language, or by a compiler that allows the unchecked warnings to suppressed _\[sic\]_. This practice is unhealthy at best.

Wiki Markup
Extending legacy classes and generifying the overriding methods fails because this is disallowed by the _Java Language Specification_ \[[JLS 2005|AA. Bibliography#JLS 05]\].

Noncompliant Code Example

This noncompliant code example compiles although it produces an unchecked warning because the raw type of the List.add() method is used (the list parameter in the addToList() method) rather than the parameterized type.

In some cases, it is possible that a compile-time unchecked warning will not be generated. According to the JLS, §4.12.2, "Variables of Reference Type" [JLS 2015]:

Note that this does not imply that heap pollution only occurs if an unchecked warning actually occurred. It is possible to run a program where some of the binaries were compiled by a compiler for an older version of the Java programming language, or by a compiler that allows the unchecked warnings to [be] suppressed. This practice is unhealthy at best.

Heap pollution can also occur if the program aliases an array variable of non-reifiable element type through an array variable of a supertype that is either raw or nongeneric. 

Noncompliant Code Example

This noncompliant code example compiles but results in heap pollution. The compiler produces an unchecked warning because a raw argument (the obj parameter in the addToList() method) is passed to the List.add() method. 

Code Block
bgColor#FFCCCC
class ListUtility {
  private static void addToList(List list, Object obj) {
    list.add(obj); // Unchecked warning
  }

  public static void main(String[] args) {
    List<String> list = new ArrayList<String> ();
    addToList(list, 42);
    System.out.println(list.get(0));  // Throws ClassCastException
  }
}

Heap pollution is possible in this case because the parameterized type information is discarded before execution. The call to addToList(list, 42) succeeds in adding an integer to list, although it is of type List<String>. This Java runtime does not throw a ClassCastException until the value is read and has an invalid type (an int rather than a String). In other words, the code throws an exception some time after the execution of the operation that actually caused the error, complicating debugging.

Even when heap pollution occurs, the variable is still guaranteed to refer to a subclass or subinterface of the declared type but is not guaranteed to always refer to a subtype of its declared type. In this example, list does not refer to a subtype of its declared type (List<String>) but only to the subinterface of the declared type (List).

Compliant Solution (Parameterized Collection)

This compliant solution enforces type safety by changing the addToList() method signature to enforce proper type checking:

Code Block
bgColor#ccccff
class ListUtility {
  private static void addToList(List<String> list, String str
Code Block
bgColor#FFCCCC

class MixedTypes {
  private static void addToList(List list, Object obj) {
    list.add(obj); // unchecked warning
  }

  public static void main(String[] args) {
    List<String> listlist.add(str);     // No warning generated
  }

  public static void main(String[] args) {
    List<String> list = new ArrayList<String> ();
    addToList(list, 1"42");
    System.out.println(list.get(0));
  }
}

When executed, this code produces an exception not because a List<String> receives an Integer but because the value returned by list.get(0) is an improper type. In other words, the code throws an exception some time after execution of the operation that actually caused the exception, complicating debuggingThe compiler prevents insertion of an object to the parameterized list because addToList() cannot be called with an argument whose type produces a mismatch. This code has consequently been changed to add a String instead of an int to the list.

Compliant Solution (

...

Legacy Code)

This compliant solution enforces type safety by changing the addToList() function signature to enforce proper type checking. It also complies by adding a String rather than an Integer.

The previous compliant solution eliminates use of raw collections, but implementing this solution when interoperating with legacy code may be infeasible.

Suppose that the addToList() method is legacy code that cannot be changed. The following compliant solution creates a checked view of the list by using the Collections.checkedList() method. This method returns a wrapper collection that performs runtime type checking in its implementation of the add() method before delegating to the back-end List<String>. The wrapper collection can be safely passed to the legacy addToList() method.

Code Block
bgColor#ccccff
class ListUtility {
  private static void addToList(List list, Object obj) {
    list.add(obj); // Unchecked warning, also throws ClassCastException
  }
Code Block
bgColor#ccccff

class Parameterized {
  private static void addToList(List<String> list, String str) {
    list.add(str);     // No warning generated
  }
  public static void main(String[] args) {
    List<String> list = new ArrayList<String> ();
    List<String> checkedList addToList= Collections.checkedList(list, "1"String.class);
    System.out.println(list.addToList(checkedList, 42);
    System.out.println(list.get(0));
  }
}

The compiler does not allow insertion of an Object once list is parameterized. Likewise, addToList() cannot be called with an argument whose type produces a mismatch.

Compliant Solution (Legacy Code)

While the previous compliant solution eliminates use of raw collections, this could be infeasible when interoperating with legacy code.

still issues the unchecked warning, which may still be ignored. However, the code now fails when it attempts to add the integer to the list, consequently preventing the program from proceeding with invalid data.

Noncompliant Code Example

This noncompliant code example compiles and runs cleanly because it suppresses the unchecked warning produced by the raw List.add() method. The printNum() method intends to print the value 42, either as an int or as a double depending on the type of the variable typeSuppose that the addToList() method was legacy code that could not be changed. The following compliant solution creates a checked view of the list by using the Collections.checkedList() method. This method returns a wrapper collection that performs runtime type checking in its implementation of the add() method before delegating to the backend List<String>. The wrapper collection can be safely passed to the legacy addToList() method.

Code Block
bgColor#ccccff#FFCCCC

class MixedTypesListAdder {
  @SuppressWarnings("unchecked")
  private static void addToList(List list, Object obj) {
    list.add(obj);  // Unchecked warning suppressed
  }

  publicprivate static <T> void mainprintNum(String[]T argstype) {
    List<String> list = new ArrayList<String> ();if (!(type instanceof Integer || type instanceof Double)) {
    List<String> checkedList = Collections.checkedList(list, String.class System.out.println("Cannot print in the supplied type");
    addToList(checkedList, 1);
}
     System.List<T> list = new ArrayList<T>();
    addToList(list, 42);
    System.out.println(list.get(0));
  }
}

The compiler still issues the "unchecked warning," which may still be ignored. However, the code now fails precisely when it attempts to add the Integer to the list, consequently preventing the program from proceeding with invalid data.

Noncompliant Code Example

This noncompliant code example compiles and runs cleanly because it suppresses the unchecked warning produced by the raw List.add() method. The printOne() method intends to print the value one, either as an int or as a double depending on the type of the variable type.


  public static void main(String[] args) {
    double d = 42;
    int i = 42;
    System.out.println(d);
    ListAdder.printNum(d);
    System.out.println(i);
    ListAdder.printNum(i);
  }
}

However, despite list being correctly parameterized, this method prints 42 and never 42.0 because the int value 42 is always added to list without being type checked. This code produces the following output:

Code Block
42.0
42
42
42

Compliant Solution (Parameterized Collection)

This compliant solution generifies the addToList() method, eliminating any possible type violations:

Code Block
bgColor#ccccff
class ListAdder {
Code Block
bgColor#FFCCCC

class BadListAdder {
  @SuppressWarnings("unchecked")
  private static void addToList(List list, Object obj) {
    list.add(obj);     // Unchecked warning
  }

  private static <T> void printOneaddToList(List<T> list, T typet) {
    if (!(type instanceof Integer || type instanceof Double)) {
      System.out.println("Cannot print in the supplied type");list.add(t);     // No warning generated
  }

  private static <T> void printNum(T type) {
    }
if (type instanceof  List<T>Integer) {
      List<Integer> list = new ArrayList<T>ArrayList<Integer>();
      addToList(list, 142);
      System.out.println(list.get(0));
    }

   public staticelse voidif main(String[] args(type instanceof Double) {
    double  List<Double> dlist = new 1ArrayList<Double>();

    int i = 1;addToList(list, 42.0);  // Will not compile with 42 instead of 42.0

      System.out.println(d(list.get(0));
     BadListAdder.printOne(d);
} else {
      System.out.println(i);
    BadListAdder.printOne(i"Cannot print in the supplied type");
    }
}

However, despite list being correctly parameterized, this method prints '1' and never '1.0' because the int value '1' is always added to list without being type checked. This code produces the following output:

Code Block

1.0
1
1
1

Compliant Solution

This compliant solution generifies the addToList() method, which eliminates any possible type violations.

  }

  public static void main(String[] args) {
    double d = 42;
    int i = 42;
    System.out.println(d);
    ListAdder.printNum(d);
    System.out.println(i);
    ListAdder.printNum(i);
  }
}

This code compiles cleanly and produces the correct output:

Code Block
42.0
42.0
42
42

If the method addToList() is externally defined (such as in a library or as an upcall method) and cannot be changed, the same compliant method printNum() can be used, but no warnings result if addToList(list, 42) is used instead of addToList(list, 42.0). Great care must be taken to ensure type safety when generics are mixed with nongeneric code.

Noncompliant Code Example (Variadic Arguments)

Heap pollution can occur without using raw types such as java.util.List. This noncompliant code example builds a list of lists of strings before passing it to a modify() method. Because this method is variadic, it casts list into an array of lists of strings. But Java is incapable of representing the types of parameterized arrays. This limitation allows the modify() method to sneak a single integer into the list. Although the Java compiler emits several warnings, this program compiles and runs until it tries to extract the integer 42 from a List<String>.

Code Block
bgColor#ffcccc
langjava
class ListModifierExample {
  public static void modify(List<String>... list
Code Block
bgColor#ccccff

class GoodListAdder {
  private static <T> void addToList(List<T> list, T t) {
    list.add(t);     // No warning generated
  }

  private static <T> void printOne(T type) {
    if (type instanceof Integer) {
      List<Integer> list = new ArrayList<Integer>();
      addToList(list, 1);
      System.out.println(list.get(0));
    }
    else if (type instanceof Double) {
      List<Double> list = new ArrayList<Double>();

      // This will not compile if addToList(list, 1) is used
      addToList(list, 1.0);

      System.out.println(list.get(0));
    }
    else {
      System.out.println("Cannot print in the supplied type");
    }
  }

  public static void main(String[] args) {
    doubleObject[] dobjectArray = 1list;
    int iobjectArray[1] = 1;
Arrays.asList(42);    System.out.println(d);
    GoodListAdder.printOne(d);
// Pollutes list, no warning

     System.out.println(i);
for (List<String> ls : list) {
      for GoodListAdder.printOne(i);
  }
}

This code compiles cleanly and produces the correct output:

Code Block

1.0
1.0
1
1

If the method addToList() is externally defined (such as in a library or as an upcall method) and cannot be changed, the same compliant method printOne() can be used, but no warnings result if addToList(1) is used instead of addToList(1.0). Great care must be taken to ensure type safety when generics are mixed with non-generic code.

Exceptions

Wiki Markup
*OBJ14-EX0* Raw types must be used in class literals. For example, because {{List<Integer>.class}} is illegal, it is permissible to use the raw type {{List.class}} \[[Bloch 2008|AA. Bibliography#Bloch 08]\].

Wiki Markup
*OBJ14-EX1* The {{instanceof}} operator cannot be used with generic types. It is permissible to mix generic and raw code in such cases \[[Bloch 2008|AA. Bibliography#Bloch 08]\].

Code Block

if(o instanceof Set) { // Raw type
  Set<?> m = (Set<?>) o; // Wildcard type
  // ...
}

Risk Assessment

Mixing generic and non-generic code can produce unexpected results and exceptional conditions.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

OBJ14-J

low

probable

medium

P4

L3

Bibliography

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="69f03ffb-5af5-4265-a3e4-610b9bc9fb77"><ac:plain-text-body><![CDATA[

[[Bloch 2008

AA. Bibliography#Bloch 08]]

Item 23: "Don't use raw types in new code"

]]></ac:plain-text-body></ac:structured-macro>

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="eecbcc15-c8b4-42f8-8776-bc0c51fecc31"><ac:plain-text-body><![CDATA[

[[Bloch 2007

AA. Bibliography#Bloch 07]]

Generics, 1. "Avoid Raw Types in New Code"

]]></ac:plain-text-body></ac:structured-macro>

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="efa160c1-f809-42ad-8514-50cf9f12faaf"><ac:plain-text-body><![CDATA[

[[Bloch 2005

AA. Bibliography#Bloch 05]]

Puzzle 88: Raw Deal

]]></ac:plain-text-body></ac:structured-macro>

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="0e1c1d4c-cfdf-4a57-8893-18e61d181c59"><ac:plain-text-body><![CDATA[

[[Darwin 2004

AA. Bibliography#Darwin 04]]

8.3 Avoid Casting by Using Generics

]]></ac:plain-text-body></ac:structured-macro>

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="cc163ba5-02b7-48ae-a528-5a1c29057b59"><ac:plain-text-body><![CDATA[

[[JavaGenerics 2004

AA. Bibliography#JavaGenerics 04]]

 

]]></ac:plain-text-body></ac:structured-macro>

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="8d620f8c-c6ae-4e3c-9356-c79a72463ca4"><ac:plain-text-body><![CDATA[

[[JLS 2005

AA. Bibliography#JLS 05]]

[Chapter 5 "Conversions and Promotions"

http://java.sun.com/docs/books/jls/third_edition/html/conversions.html]

]]></ac:plain-text-body></ac:structured-macro>

 

§4.8 "Raw Types"

 

§5.1.9 "Unchecked Conversion"

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="5142053a-8b68-4110-8504-187ce5175ec9"><ac:plain-text-body><![CDATA[

[[Langer 2008

AA. Bibliography#Langer 08]]

Topic 3, "[Coping with Legacy

http://www.angelikalanger.com/GenericsFAQ/FAQSections/ProgrammingIdioms.html#Topic3]"

]]></ac:plain-text-body></ac:structured-macro>

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="65c5e4cd-002f-46ac-90a4-4a2bd3e8f609"><ac:plain-text-body><![CDATA[

[[Naftalin 2006

AA. Bibliography#Naftalin 06]]

Chapter 8, "Effective Generics"

]]></ac:plain-text-body></ac:structured-macro>

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="f5df11d4-e1e2-48b0-9065-fa4afcb4a551"><ac:plain-text-body><![CDATA[

[[Naftalin 2006b

AA. Bibliography#Naftalin 06b]]

"Principle of Indecent Exposure"

]]></ac:plain-text-body></ac:structured-macro>

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="b8687043-1921-4ae0-8ac8-80c13ac218dc"><ac:plain-text-body><![CDATA[

[[Schildt 2007

AA. Bibliography#Schildt 07]]

"Create a checked collection"

]]></ac:plain-text-body></ac:structured-macro>

(String string : ls) {          // ClassCastException on 42
        System.out.println(string);
      }
    }
  }
 
  public static void main(String[] args) {
    List<String> s = Arrays.asList("foo", "bar");
    List<String> s2 = Arrays.asList("baz", "quux");
    modify( s, s2);                       // Unchecked varargs warning
  }
}

This program produces the following output:

Code Block
foo
bar
Exception in thread "main" java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String
	at ListModifierExample.modify(Java.java:13)
	at ListModifierExample.main(Java.java:25)
	at Java.main(Java.java:33)

Noncompliant Code Example (Array of Lists of Strings)

This noncompliant code example is similar, but it uses an explicit array of lists of strings as the single parameter to modify(). The program again dies with a ClassCastException from the integer 42 injected into a list of strings.

Code Block
bgColor#ffcccc
langjava
class ListModifierExample {
  public static void modify(List<String>[] list) {
    Object[] objectArray = list;          // Valid
    objectArray[1] = Arrays.asList(42);   // Pollutes list, no warning

    for (List<String> ls : list) {
      for (String string : ls) {          // ClassCastException on 42
        System.out.println(string);
      }
    }
  }
 
  public static void main(String[] args) {
    List<String> s = Arrays.asList("foo", "bar");
    List<String> s2 = Arrays.asList("baz", "quux");
    List list[] = {s, s2};
    modify(list);                         // Unchecked conversion warning
  }
}

Compliant Solution (List of Lists of Strings)

This compliant solution uses a list of lists of strings as the argument to modify(). This type safety enables the compiler to prevent the modify() method from injecting an integer into the list. In order to compile, the modify() method instead inserts a string, preventing heap pollution.

Code Block
bgColor#ccccff
langjava
class ListModifierExample {
  public static void modify(List<List<String>> list) {
    list.set( 1, Arrays.asList("forty-two")); // No warning

    for (List<String> ls : list) {
      for (String string : ls) {            // ClassCastException on 42
        System.out.println(string);
      }
    }
  }
 
  public static void main(String[] args) {
    List<String> s = Arrays.asList("foo", "bar");
    List<String> s2 = Arrays.asList("baz", "quux");
    List<List<String>> list = new ArrayList<List<String>>();
    list.add(s);
    list.add(s2);
    modify(list);
  }
}

Note that to avoid warnings, we cannot use Arrays.asList() to build a list of lists of strings because that method is also variadic and would produce a warning about variadic arguments being parameterized class objects.

Risk Assessment

Mixing generic and nongeneric code can produce unexpected results and exceptional conditions.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

OBJ03-J

Low

Probable

Medium

P4

L3

Automated Detection

ToolVersionCheckerDescription
Parasoft Jtest
Include Page
Parasoft_V
Parasoft_V
CERT.OBJ03.AGBPTAvoid conversions from parameterized types to raw types

Bibliography

[Bloch 2008]

Item 23, "Don't Use Raw Types in New Code"

[Bloch 2007]

[Bloch 2005]

Puzzle 88, "Raw Deal"

[Darwin 2004]

Section 8.3, "Avoid Casting by Using Generics"

[JavaGenerics 2004]


[Java Tutorials]

"Heap Pollution"

[JLS 2015]

§4.8, "Raw Types"
§4.12.2, "Variables of Reference Type"
Chapter 5, "Conversions and Promotions"

§5.1.9, "Unchecked Conversion"

[Langer 2008]

Topic 3, "Coping with Legacy"

[Naftalin 2006]

Chapter 8, "Effective Generics"

[Naftalin 2006b]

"Principle of Indecent Exposure"

[Schildt 2007]

"Create a Checked Collection"


...

Image Added Image Added Image AddedOBJ13-J. Preserve dependencies in subclasses when changing superclasses      04. Object Orientation (OBJ)      OBJ15-J. Write garbage-collection-friendly code