What is Heap Pollution?
Heap pollution implies that we have bad data in our heap memory. In Java language, heap pollution is a situation that occurs when a variable of parameterized type points to an object that is not of that parameterized type.
How is Heap Pollution detected?
At the run-time, there is a chance of arising heap pollution that will cause ClassCastException. Heap pollution means the bad data in the heap memory. Here bad data is an object of type X but an object of type Y is expected and it will throw ClassCastException at runtime.
Lets understand the heap pollution with program:
Compile Time Console:
prog.java:12: warning: [unchecked] unchecked cast List listOfInteger = (List)(Object)listOfString; ^ required: List found: Object 1 warning
Exception in thread “main” java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer
How to deal with Heap Pollution?
Compile Time Console:
prog.java:4: warning: [unchecked] Possible heap pollution from parameterized vararg type List public static void merge(List... stringList) ^ prog.java:23: warning: [unchecked] unchecked generic array creation for varargs parameter of type List merge(list1, list2, list3); ^ 2 warnings
Exception in thread "main" java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String at Geeks.merge(File.java:10) at Geeks.main(File.java:23)
Note: If we don’t want warnings at the compiler time then we can use @SafeVarargs annotation above the method. If we know that the method doesn’t contain any heap pollution situation then you can annotate it with @SafeVarargs to suppress the warning. It does not mean that it will allow our code for heap pollution. It means that if in the code, there is a chance of Heap pollution, it will throw ClassCastException at the run time.
How to prevent Heap pollution situations?
We cant prevent Heap pollution situations, but we can follow a few rules that can help us to prevent heap pollution like:
- Don’t use varargs parameters with generic types or cast an Object array to an array of a generic type.
- Not to expose the varargs parameter or the generic array to any other method.
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.