[Java] Heap Pollution

Heap Pollution

힙 오염이란 매개변수화 타입의 변수가 타입이 다른 객체를 참조할 때 발생한다. 이로 인하여 런타임에 종종 ClassCastException이 발생한다.

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. This situation is normally detected during compilation and indicated with an unchecked warning. Later, during runtime heap pollution will often cause a ClassCastException.

A source of heap pollution in Java arises from the fact that type arguments and variables are not reified at run-time. As a result, different parameterized types are implemented by the same class or interface at run time. Indeed, all invocations of a given generic type declaration share a single run-time implementation. This results in the possibility of heap pollution.

Under certain conditions, it is possible that a variable of a parameterized type refers to an object that is not of that parameterized type. The variable will always refer to an object that is an instance of a class that implements the parameterized type.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class HeapPollutionDemo
{
public static void main(String[] args)
{
Set s = new TreeSet<Integer>();
Set<String> ss = s; // unchecked warning
s.add(new Integer(42)); // another unchecked warning
Iterator<String> iter = ss.iterator();
while (iter.hasNext())
{
String str = iter.next(); // ClassCastException thrown
System.out.println(str);
}
}
}
Author: Song Hayoung
Link: https://songhayoung.github.io/2020/08/12/Languages/Java/heappollution/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.