Search code examples
java-native-interfacenativejava

how jdk1.0 lacked clean separation between native and Java code?


From IBM Link :

The JDK 1.0 release included an earlier native-method interface that lacked clean separation between native and Java code. In this interface, natives would reach directly into JVM structures and so could not be portable across JVM implementations, platforms, or even versions of the JDK. Upgrading an application with a substantial number of natives using the JDK 1.0 model was expensive, as was developing natives that could run with multiple JVM implementations.

What is meant by natives would reach directly into JVM structures and so could not be portable across JVM implementations ? I don't understand this.


Solution

  • The documentation for the current JNI contains this interesting bit about the old interface:

    JDK 1.0 was shipped with a native method interface. Unfortunately, there were two major reasons that this interface was unsuitable for adoption by other Java VMs.

    First, the native code accessed fields in Java objects as members of C structures. However, the Java Language Specification does not define how objects are laid out in memory. If a Java VM lays out objects differently in memory, then the programmer would have to recompile the native method libraries.

    ...

    This means that the native code could directly access the values of objects in memory, instead of going through some API. That's the equivalent of direct access to a field in Java, as opposed to using getters/setters. This means that the underlying layout of the fields could never be changed without breaking compatibility with any code that uses that old native interface.

    I've found a copy of the native method tutorial from the JDK 1.0.2 here. It includes a section on handling Java objects from native code.

    The modern JNI gives access to Java object fields only via method calls. This way the layout of objects and many other things can change without breaking compatibility.