Sunday, October 18, 2015

Java: When the compiler crashes the plane

Software design principles on compiled programming languages tend to have one rule in common; Compiler errors over runtime errors. A religiously followed rule. It's a dogma (although based on legitimate reasons). You should always program in a way that most errors would be reported from the compiler and your logic tested by unit testing. Sometimes little things slip through though.

The following scenario describes an easy to do mistake in Java and highlights some good practice to avoid crashing that plane.

Pre-requisites:



Open intelliJ and setup a java project with the following (adapt to match your system):





The example code is this:

import java.util.concurrent.ConcurrentHashMap;


public class FunWithMaps {

    public static void main(String[] args) {
        ConcurrentHashMap map = new ConcurrentHashMap();

        map.put("1", 1);

        System.out.println(map.keySet().getClass());
    }
}

Run. You'll get the following error:

Exception in thread "main" 
java.lang.NoSuchMethodError: 
java.util.concurrent.ConcurrentHashMap.keySet()Ljava/util/concurrent/ConcurrentHashMap$KeySetView;

So, the compiler used java 8 API and didn't complain despite the fact that we set it 
to compile to java 7. But that was the bytecode version and the java 8 API that was in
the compile classpath didn't cause any problems. 

Consider that this scenario is what the continuous integration (CI) might have. 
This imaginary CI system builds your production level code but you - as a programmer - 
have no control over it. Then, the ConcurrentHashMap code would succeed on your IDE 
(because you would be compiling with java 7 targeting java 7) but the CI would be compiling 
java 8 generating java 7 bytecode without having java 7 API in the classpath. The runtime environment
 would use java 7.

You wouldn't know, the compiler wouldn't know, and the crash would rely on the testing environment
 to be caught. That scenario might cause you a late runtime crash on a live environment.

Let's see the bytecode a bit and see if we get what we expect, i.e. a call to the keySet method that returns the KeySetView.

Open your generated class file with Java bytecode editor.



On line 13, this is quite obvious. When running with java 7 you don't get any error until line 13 is executed by jvm and it tries to find that method, which doesn't exist on java 7. So how can we avoid this with a bit of good practice (although, having in compile time classpath an API of a different version that the one on runtime is the most obvious mistake that needs fixing). But we want our code to be as safe as possible and work even in situations where simple API changes won't affect it.

Let's change the left hand side to the interface definition. The Map.

 import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


public class FunWithMaps {

    public static void main(String[] args) {
        Map map = new ConcurrentHashMap();

        map.put("1", 1);

        System.out.println(map.keySet().getClass());
    }
}

Before running it, make a build and see the bytecode. It's now a bit different.



As expected, the compiler now generated the bytecode according to the interface visibility of the method.
If you run it now with java 7 it will not fail and will output:
class java.util.concurrent.ConcurrentHashMap$KeySet

Switch run configurations to jre 8. Run again and you get what you expected:
class java.util.concurrent.ConcurrentHashMap$KeySetView


It's always a good practice to define your variables with the highest superclass or interface 
possible, especially if you are using an external API (which is pretty much always the case). 
Interfaces rarely change or at least they change less frequently from implementation code.


That should as well settle the argument of using on the left hand side the instantiating class 
in the variable definition or their superclass (interface they implement).

1 comment: