• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Heap Pollution

 
Anirudh Vyas
Ranch Hand
Posts: 93
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

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.

Regards
Vyas, Anirudh
 
Tim Holloway
Saloon Keeper
Pie
Posts: 18098
50
Android Eclipse IDE Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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:


Or



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

 
Vlado Zajac
Ranch Hand
Posts: 245
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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).
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic