Thursday, 20 October 2016

Potential heap pollution via varargs parameter

Reifiable versus Non-Reifiable

Type erasure is an important "feature" of Generics in Java. It means generics are not available at runtime, as they are effectively removed during compiling.

The reference in [1] has a much better explanation.

To quote:
“A reifiable type is a type whose type information is fully available at runtime.”
“Non-reifiable types are types where information has been removed at compile-time by type erasure.”

Generics versus Arrays

In Java, generics are non-reifiable and arrays are reifiable.

Problems can occur when we combine these two together.

Combining these two together can happen when using the varargs construction in Java.

The reason for this is that the varargs way of using method parameters is translated within the method as a array.

This can cause Heap pollution2 when combined with Generics.

As the compiler doesn't know when this happens (it depends on how the method deals with it), it throws out the warning.

Hence the need for the @SafeVarargs3 annotation for those methods where the software designers are certain the problem does not occur.

References

[1] Non-Reifiable Types
http://docs.oracle.com/javase/tutorial/java/generics/nonReifiableVarargsType.html
[2] 9.6.3.7. @SafeVarargs
http://docs.oracle.com/javase/specs/jls/se7/html/jls-9.html#jls-9.6.3.7
[3] Oracle JavaDoc - SafeVarargs
http://docs.oracle.com/javase/7/docs/api/java/lang/SafeVarargs.html
StackOverflow - Potential heap pollution via varargs parameter
http://stackoverflow.com/questions/12462079/potential-heap-pollution-via-varargs-parameter

No comments:

Post a Comment