When you see the word "Java" describing an application, whether it be an application server, a relational database engine, or an e-commerce solution, a favorite marketing catch phrase is "100% Java." In fact, in the late 90's, Sun Microsystems even had a 100% Pure Java application certification process and branding program. The idea was to provide developers with a set of standards and a review process to make sure their applications truly conformed to the "Write Once Run Anywhere" (WORA) mantra.
Although Sun has discontinued, or should I say "deprecated," its 100% Pure Java certification program, you can still read the certification cookbook in the Sun product archives. It contains some great examples and guidelines on how to keep your applications portable as well as some interesting insights into what exactly portability is. Often, a portable application is defined as one that "behaves exactly the same way on all platforms"; however, to use this definition would be naive. As Sun points out in the certification cookbook, what if you have some logic in the application that branches based on the underlying OS? Does this mean your application is not portable? This sort of situation comes up all the time when dealing with GUIs. So if you enjoy this kind of debate as much as I do, give the certification cookbook a quick read.
The main reason I reference the 100% Pure Java application certification program here is that it even allowed for some wiggle room under the term "variance." A variance is something that is not compliant with the certification program, but that Sun deemed as being acceptable anyway. Sun understands that, in certain situations, you have to make exceptions to the rules.
Tradeoffs
Software development is all about tradeoffs. The classic tradeoff is time versus space. I can almost always write an algorithm to accomplish a task in less time, but it usually requires more space. If I have a very small application to write, I could write the whole thing quickly in one monolithic hunk; however, I have traded reusability--and more importantly, maintainability--for getting done quickly. Or suppose I need an application to be extremely fast. I can write it in assembly language; however, to do so, I have to sacrifice speed of development, portability, and a bottle of Advil.
Managing tradeoffs in software development is essential, but tradeoffs are not always as obvious as those listed above. My favorite example of this is database indexes. Suppose you have an SQL query, and its execution time is slowing down your application. You examine the code and the database and determine that you should add an index because you are accessing the data by a fairly unique value on a particular field. Here is the classic tradeoff of space for time: You add space for the index, and you save time on the query. However, there is another tradeoff in that indexes must be maintained. Anytime the value of an indexed field is changed through an insert, update, or delete, the index must also be updated, which, of course, takes time. So, when analyzing tradeoffs, you have to be sure that you know what the real tradeoffs are.
Another classic tradeoff is portability versus performance and/or functionality. We can sometimes squeeze out extra performance and/or functionality by using native code, but the tradeoff is portability. Again, carefully scrutinize this situation when it arises, and make sure you are aware of all the tradeoffs.
Integrating Non-Java Programs
Eventually, we all get the request or requirement in our Java programming careers to integrate into our applications some bit of functionality that is not written in Java. If you haven't gotten one of these requests yet, be assured that it is only a matter of time. As I see it, you generally have three choices of how to deal with this sort of situation. The first choice is to port whatever it is to Java. This is often the ideal solution for the long term, but it can be cost-prohibitive in that it may take significant time and resources, and it may introduce risk in the form of new bugs. The second choice is to hide the functionality behind a well-defined interface, such as a Java Web service. This is a good solution if the functionality is complicated, and it also allows you to later port it to Java without affecting the rest of the application that it is integrated with. The third choice and focus of this article is to wrap the functionality in a Java Native Interface (JNI). This is the best solution when the code being called needs to run within the same process as your Java application. Actually, there are a number of other ways to integrate with non-Java programs, such as using JDBC, but from an architectural point of view, the best solutions usually fall into one of the three categories I mentioned.
Java Native Interface (JNI)
JNI comes in two reciprocal flavors, native method and invocation interface. A native method is one in which you call a non-Java method from within a Java VM. With invocation, you call Java from within a native method. A native method call is the more common of the two because it is far more likely that Java applications call other applications than other applications call Java applications. So let's do an example of that using a C/C++ native call. Here are the general steps that you will need to follow to create an application:
1. Create a Java class that contains a declaration for the native method as well as some code to load the library that will contain it.
2. Compile the Java class.
3. Use javah to generate a .h file, which will contain the declaration of the native function. Note: We say "method" when we are referring to Java and "function" when we are referring to C/C++, but they are actually the same thing.
4. Create a .c (or .cpp) file that contains the definition of the function declared in the .h file.
5. Compile the C/C++ function to create a library.
6. Run the Java application.
For this sample Java application, we will create a Java method that calls a C function, which returns a string that the Java application will then print to the console. This example uses Microsoft Visual Studio 6.0.
Step 1: Create the Java Class
Here is the source code for our Java class:
|
Here, we have created a class called JNIExample, which declares one private method called goNative(), which returns a string. In the declaration of the goNative() method, note the use of the native modifier nestled between the access modifier private and the return type String. Also note the use of the semicolon (;) at the end of the method declaration where you would normally expect to see a definition of the method enclosed in curly braces. Those of you familiar with C and C++ will notice that this is syntactically similar to the way C and C++ does function prototypes. semi-colon (We also declared a library loader within a static block, which will load our native library. Since we are working under Windows, this will be a .dll file called MyNativeLibrary.dll. In addition, the class contains a main() method for staring the application, which will create an instance of our class, invoke its goNative() method, and then echo the results to the console.
Step 2: Compile the Java Class
Nothing fancy to do here. Just compile the source code using javac, or pull the source code into your favorite IDE and do a build.
Step 3: Use javah to Generate a .h File
To generate the .h file, simply use this command:
A couple of things to note here: First, anytime you change the Java source that this .h file is based on, you should recompile it and then rerun javah on it. Second, be sure that the .class file--in this case, JNIExample.class--is in your classpath. Running this command on the above source file under JDK1.3 produces the following .h file:
|
Please heed the warning and do not edit this file directly. If you do edit it, all your changes will be lost the next time you run javah.
Step 4: Create a .c File
Now that we have our .h header file that declares our native function call, we can create our C source file that defines it:
|
I created a Win32 DLL project called MyNativeLibrary in Visual Studio 6.0, imported the .h file generated above, and then added the JNIExample.cpp file above.
Step 5: Compile the C/C++ Function to Create a Library
To generate MyNativeLibrary.dll, be sure to include jni.h and jni_md.h in your include path and then compile the project using a rebuild all.
Step 6: Run the Java Application
After copying MyNativeLibrary.dll to the same directory as JNIExample.class, run the application using this command:
The result should be that the string "Native" is printed out to the console.
There You Have It
Six easy steps and a dozen lines of code later, you have a Java application calling native C code. The similarities between the JNI process and JAX-RPC are striking. For a quick review of JAX-RPC, read "Java Journal: Web Services Developer Pack JAX-RPC" . The idea is pretty much the same. Declare an interface, run an application against it that generates the code to handle the details of the interaction, and then write the code that talks to the generated code. The best part is that the code generators handle all the messy details, and we are programming to an interface.
Going Native
A cursory review of the JNI documentation reveals that JNI was originally targeted at applications that needed to call C and C++ code. This is where the "Native" in the Java Native Interface comes from. However, this was a bit short-sighted, as there are other languages, such as Smalltalk, that compile to byte code and execute in a Virtual Machine, just like Java does. So maybe the real name should have been Non-Java Interface rather than Java Native Interface. In fact, JNI is often referenced as the solution to integrate legacy code, but really it is far more than that. It is the way to make Java interact with any other language, legacy or not.
Interfaces
Those of you who are frequent readers of my column know that I have two basic principles that I follow in all my programming endeavors:
1. Favor composition over inheritance
2. Program to an interface
Favoring composition over inheritance is another topic, but programming to an interface is exactly what we are doing here. Almost every significant aspect of object-oriented programming--whether it be polymorphism, encapsulation, information hiding, or even most design patterns--is a form of programming to an interface. The general rule is to keep the implementation behind an interface. Then, as long as you don't change the interface itself, you can change the implementation as much as you want.
It should be noted that the two basic principles of "favor composition over inheritance" and "program to an interface" were drilled into my head many years ago by my favorite college professor and mentor Dr. Roger Whitney from San Diego State University. For more information on Whitney, you can visit his home page.
Keeping Our Interfaces Clean
In our example above, the Java side of the application has a very clean interface. However, we could improve upon it. If we want to someday change out our code for a non-native version, we can just change a few lines of code. Or even better, we can create a generic Java interface for our class to implement. Then, as long as our application accesses only our native code through this interface, when it's time to change out the native code, all we have to do is create a new all-Java implementation of the interface and change the code that actually instantiates the class to instantiate our new class. This way, we accomplish our goal of removing the native call without actually changing any of the code. On the C side of the application, we have to do a lot of translation between C and Java versions of structures. My advice here is keep data types as simple as possible and do the translation as close to the interface as possible. You don't want all the Java structures, such as jstrings, invading your C code. For those of you familiar with design patterns, this is an excellent place for the Adaptor pattern.
References
Sun really should be commended for the number of books that it puts online. You can either browse these books in HTML format or download the entire PDF. For JNI, you can get the entire Java Native Interface: Programmer's Guide and Specification.
Conclusion
Even Sun realizes that you can't be 100% Java 100% of the time, and that is exactly the reason for the built-in JNI. The JNI is a powerful, easy-to-use API. Just be sure you understand that, by using it, you might lose your ability to easily port to another platform. To use JNI, just follow the six steps outlined in this article, repeating steps as necessary when you modify the underlying base source code. JNI is just one of several possible solutions for integrating non-Java code and is best suited for when code needs to run locally as part of the same process as the Java application itself. Generating JNI interfaces is very similar to generating JAX-RPC interfaces, and, as with JAX-RPC, the code generators do all the heavy lifting for you. Even if you never do any JNI programming at all, remember the words of my mentor Dr. Roger Whitney: "Always program to an interface."
Michael J. Floyd is an extreme programmer and the Software Engineering Manager for DivXNetworks. He is also a consultant for San Diego State University and can be reached at
LATEST COMMENTS
MC Press Online