It's not a secret anymore!
The moose likes Performance and the fly likes Heap Pollution Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Performance
Bookmark "Heap Pollution" Watch "Heap Pollution" New topic

Heap Pollution

Anirudh Vyas
Ranch Hand

Joined: Oct 23, 2006
Posts: 93

I was looking through JLS 3rd edition and found this interesting topic :

Heap Pollution

Can someone give a clear but ellaborate example in context of exactly what happens or what is meant by heap pollution? meaning, as the JLS says :
so if I've got:

List l = new ArrayList<Number>();
List<String> ls = l; // cause unchecked warning (as said in JLS, but i am thinking above statement would also give a warning, since its a raw type).

JLS goes on to say that :
This would cause heap pollution because you cannot infer the type at compile time and runtime, my question is, so if we cannot infer the type, then what? how does it affect the heap?

Sorry if the question sounds dumb.

Vyas, Anirudh

Vyas, Anirudh
Tim Holloway
Saloon Keeper

Joined: Jun 25, 2001
Posts: 17417

I read the wikipedia explanation, and it's clear as mud. And what kind of word is "reification"? "Instantiation" is bad enough, and don't even get me started on "proactive" (nobody seems to simply take an active role anymore).

OK, returning blood pressure to normal - or as close as I get anymore:

At first glance, your code would appear to be a candidate for a compiler error, but actually not. The problem lies in reducing the object type down to a generic List then promoting it back up again to a type incompatible with the original declaration. In your example, that should produce a warning, but in the real world, the two statements might be sufficiently distant that the compiler can't deduce anything.

On the inside, what I think this means is that the generated code knows that "l" is a List in general, but isn't allowed to do any compile-time checking for anything more, and its run-time options are reduced as well.

Consider this:


No harm done. The danger is if your original case is also possible (say, for example something like this:

An IDE is no substitute for an Intelligent Developer.
Vlado Zajac
Ranch Hand

Joined: Aug 03, 2004
Posts: 245
Consider this code, which compiles with unchecked warning but no errors

Line 4 produces ClassCastException.

Heap pollution occurs in line 3. After line 3 the list ls contains incorrect item (it is List<String> but contains an Integer).
I agree. Here's the link:
subject: Heap Pollution
It's not a secret anymore!