patternjavaCritical
Possible heap pollution via varargs parameter
Viewed 0 times
possiblepollutionviaparametervarargsheap
Problem
I understand this occurs with Java 7 when using varargs with a generic type;
But my question is..
What exactly does Eclipse mean when it says "its use could potentially pollute the heap?"
And
How does the new
But my question is..
What exactly does Eclipse mean when it says "its use could potentially pollute the heap?"
And
How does the new
@SafeVarargs annotation prevent this?Solution
Heap pollution is a technical term. It refers to references which have a type that is not a supertype of the object they point to.
This can lead to "unexplainable"
However, if the method actually is not safe, users will no longer be warned.
List listOfAs = new ArrayList<>();
List listOfBs = (List)(Object)listOfAs; // points to a list of AsThis can lead to "unexplainable"
ClassCastExceptions.// if the heap never gets polluted, this should never throw a CCE
B b = listOfBs.get(0);@SafeVarargs does not prevent this at all. However, there are methods which provably will not pollute the heap, the compiler just can't prove it. Previously, callers of such APIs would get annoying warnings that were completely pointless but had to be suppressed at every call site. Now the API author can suppress it once at the declaration site.However, if the method actually is not safe, users will no longer be warned.
Code Snippets
List<A> listOfAs = new ArrayList<>();
List<B> listOfBs = (List<B>)(Object)listOfAs; // points to a list of As// if the heap never gets polluted, this should never throw a CCE
B b = listOfBs.get(0);Context
Stack Overflow Q#12462079, score: 330
Revisions (0)
No revisions yet.