Java 8 Compiler is More Strict

I was trying to build Apache Hadoop 2.0.3-alpha with the ARM Java 8 Preview (to test out hard-float build support, which needs a Hadoop build fix), and I hit a compile error in InputSampler.java in the Map/Reduce code. It seems that the Java 8 compiler won’t allow a raw type to be used in a context where previous versions did. Stripping that file down to the essentials:

public class InputSampler<K,V> {
  public interface InputFormat<K,V> {
  }
  public interface Sampler<K,V> {
    K[] getSample(InputFormat<K,V> inf);
  }
  public static <K,V> void writePartitionFile(Sampler<K,V> sampler) {
    final InputFormat inf = null; // Yuck, a raw type!
    K[] samples = sampler.getSample(inf);
  }
}

This code fails to compile with Java 8 (regardless of any -source setting):

$ java -version
java version "1.8.0-ea"
Java(TM) SE Runtime Environment (build 1.8.0-ea-b36e)
Java HotSpot(TM) Server VM (build 25.0-b04, mixed mode)
$ javac InputSampler.java
InputSampler.java:9: error: incompatible types: Object[] cannot be converted to K[]
    K[] samples = sampler.getSample(inf);
                                   ^
  where K,V are type-variables:
    K extends Object declared in method <K,V>writePartitionFile(Sampler<K,V>)
    V extends Object declared in method <K,V>writePartitionFile(Sampler<K,V>)
Note: InputSampler.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
1 error

Compilation succeeds with Java 7 (with a warning):

$ java -version
java version "1.7.0_11"
Java(TM) SE Runtime Environment (build 1.7.0_11-b21)
Java HotSpot(TM) 64-Bit Server VM (build 23.6-b04, mixed mode)
$ javac InputSampler.java
Note: InputSampler.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.

The code above is definitely invalid according to JLS7 15.12.2.6, which demands that methods applicable via unchecked conversion have their return type erased, but making breaking strictness changes in the compiler is likely going to slow the adoption of Java 8.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.