Monday 23 June 2014

Heap Pollution

Heap pollution can only occur if the program performed some operation involving a raw type that would give rise to a compile-time unchecked warning (or) if the program aliases an array variable of non-reifiable element type through an array variable of a supertype which is either raw or non-generic.

import java.util.*;
class HeapPollution1{

 static void call(List<String>... stringLists) {
  String s = stringLists[0].get(0); 
  System.out.println(s);
 }

 public static void main(String args[]){  
  List<String> myList1 = new ArrayList<> ();
  List<String> myList2 = new ArrayList<> ();
  
  myList1.add("Hi");
  myList2.add("Hi");
  
  call(myList1, myList2);
  
 }
}

Output
Hi

Will try to add below three lines to method "call".

Object[] array = stringLists;
List<Integer> tmpList = Arrays.asList(42);
array[0] = tmpList;

import java.util.*;
class HeapPollution1{

 static void call(List<String>... stringLists) {
  Object[] array = stringLists;
  List<Integer> tmpList = Arrays.asList(42);
  array[0] = tmpList; // (1)
  String s = stringLists[0].get(0); // (2)
  System.out.println(s);
 }

 public static void main(String args[]){  
  List<String> myList1 = new ArrayList<> ();
  List<String> myList2 = new ArrayList<> ();
  
  myList1.add("Hi");
  myList2.add("Hi");
  
  call(myList1, myList2);
 }
}


Output
Exception in thread "main" java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String
        at HeapPollution1.call(HeapPollution1.java:8)
        at HeapPollution1.main(HeapPollution1.java:19)


Heap pollution occurs at (1) because a component in the stringLists array that should refer to a List<String> now refers to a List<Integer>. There is no way to detect this pollution in the presence of both a universal supertype (Object[]) and a non-reifiable type (the declared type of the formal parameter, List<String>[]). No unchecked warning is justified at (1); nevertheless, at run time, a ClassCastException will occur at (2).


Related Links





                                                             Home

No comments:

Post a Comment