Why JVM can not type infer type params but javac can do?

Maurizio Cimadamore maurizio.cimadamore at oracle.com
Thu Jan 8 11:35:40 UTC 2015

On 08/01/15 08:54, Ali Ebrahimi wrote:
> Hi, maybe this is stupid question, but want to ask and what is requirements
> for this?
> Array instantiation sample:
> public <any T> T[] newArray(int){
>          return new T[0];
> }
> even for non-any T:
> public <T> T[] newArray(int){
>          return new T[0];
> }
> With thousands number of optimization and inlining mechanics equipped in
> jvm, What is the reasoning behind not allowing to jvm to be aware of
> generics info emitted in classfilles?
> Why jvm should not able do following inlining?
> String[] strs =  newArray(int) => String[] strs = new String[0];
> I mean even in jitted code.
> I think some time ago I read some papers in similar area.
Well, you probably don't want the types of your arrays to change 
depending on mere optimizations; the type of the array is important - if 
it's Object[] then you can stuff anything you like into it and the VM 
will not bark; but if it's String[] then the VM will be much more 
paranoid about it. And you can't have a program that runs correctly or 
fails depending on which kind of optimizations have been applied.

So, the question maybe is: why doesn't the VM do all the type lifting 
that is required in order to figure out that T means String? Well, one 
good reason is that answering such question is not simple and it 
involves a lot of type-system machinery - which the compiler already 
has. If we were to replicate this logic in the VM, it will turn out to 
be a maintenaince pain - as we will have then to worry to keep javac and 
the JVM type-system routines in sync. Since javac has all the info (as 
your email subject suggests), it is way more straightforward to just add 
an 'hint' that tells the VM how to reconstruct the type of T. Also, 
other languages might have different ideas of how inference should be 
performed and find the java-like behavior too strict/or simply insufficient.


More information about the valhalla-dev mailing list