22
Sun, Dec
3 New Articles

Java Journal: Java Native Interface (JNI)

Java
Typography
  • Smaller Small Medium Big Bigger
  • Default Helvetica Segoe Georgia Times

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:

// JNIExample.java
public class JNIExample
{
  public static void main(String[] args)
  {
    JNIExample myExample = new JNIExample();
    String nativeCallResults = myExample.goNative();
    System.out.println(nativeCallResults);
  }

  private native String goNative();

  static
  {
    System.loadLibrary("MyNativeLibrary");
  }
}


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:

javah –jni JNIExample 


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:

/* DO NOT EDIT THIS FILE - it is machine generated */
#include 
/* Header for class JNIExample */

#ifndef _Included_JNIExample
#define _Included_JNIExample
#ifdef __cplusplus
extern "C" {
#endif
/*
 * Class:     JNIExample
 * Method:    goNative
 * Signature: ()Ljava/lang/String;
 */
JNIEXPORT jstring JNICALL Java_JNIExample_goNative
  (JNIEnv *, jobject);

#ifdef __cplusplus
}
#endif
#endif


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:

// JNIExample.cpp
#include "JNIExample.h"

JNIEXPORT jstring JNICALL Java_JNIExample_goNative
  (JNIEnv *env, jobject obj)
{
  return env->NewStringUTF("Native");
}


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:

java JNIExample


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 This email address is being protected from spambots. You need JavaScript enabled to view it..

BLOG COMMENTS POWERED BY DISQUS

LATEST COMMENTS

Support MC Press Online

$

Book Reviews

Resource Center

  • SB Profound WC 5536 Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application. You can find Part 1 here. In Part 2 of our free Node.js Webinar Series, Brian May teaches you the different tooling options available for writing code, debugging, and using Git for version control. Brian will briefly discuss the different tools available, and demonstrate his preferred setup for Node development on IBM i or any platform. Attend this webinar to learn:

  • SB Profound WP 5539More than ever, there is a demand for IT to deliver innovation. Your IBM i has been an essential part of your business operations for years. However, your organization may struggle to maintain the current system and implement new projects. The thousands of customers we've worked with and surveyed state that expectations regarding the digital footprint and vision of the company are not aligned with the current IT environment.

  • SB HelpSystems ROBOT Generic IBM announced the E1080 servers using the latest Power10 processor in September 2021. The most powerful processor from IBM to date, Power10 is designed to handle the demands of doing business in today’s high-tech atmosphere, including running cloud applications, supporting big data, and managing AI workloads. But what does Power10 mean for your data center? In this recorded webinar, IBMers Dan Sundt and Dylan Boday join IBM Power Champion Tom Huntington for a discussion on why Power10 technology is the right strategic investment if you run IBM i, AIX, or Linux. In this action-packed hour, Tom will share trends from the IBM i and AIX user communities while Dan and Dylan dive into the tech specs for key hardware, including:

  • Magic MarkTRY the one package that solves all your document design and printing challenges on all your platforms. Produce bar code labels, electronic forms, ad hoc reports, and RFID tags – without programming! MarkMagic is the only document design and print solution that combines report writing, WYSIWYG label and forms design, and conditional printing in one integrated product. Make sure your data survives when catastrophe hits. Request your trial now!  Request Now.

  • SB HelpSystems ROBOT GenericForms of ransomware has been around for over 30 years, and with more and more organizations suffering attacks each year, it continues to endure. What has made ransomware such a durable threat and what is the best way to combat it? In order to prevent ransomware, organizations must first understand how it works.

  • SB HelpSystems ROBOT GenericIT security is a top priority for businesses around the world, but most IBM i pros don’t know where to begin—and most cybersecurity experts don’t know IBM i. In this session, Robin Tatam explores the business impact of lax IBM i security, the top vulnerabilities putting IBM i at risk, and the steps you can take to protect your organization. If you’re looking to avoid unexpected downtime or corrupted data, you don’t want to miss this session.

  • SB HelpSystems ROBOT GenericCan you trust all of your users all of the time? A typical end user receives 16 malicious emails each month, but only 17 percent of these phishing campaigns are reported to IT. Once an attack is underway, most organizations won’t discover the breach until six months later. A staggering amount of damage can occur in that time. Despite these risks, 93 percent of organizations are leaving their IBM i systems vulnerable to cybercrime. In this on-demand webinar, IBM i security experts Robin Tatam and Sandi Moore will reveal:

  • FORTRA Disaster protection is vital to every business. Yet, it often consists of patched together procedures that are prone to error. From automatic backups to data encryption to media management, Robot automates the routine (yet often complex) tasks of iSeries backup and recovery, saving you time and money and making the process safer and more reliable. Automate your backups with the Robot Backup and Recovery Solution. Key features include:

  • FORTRAManaging messages on your IBM i can be more than a full-time job if you have to do it manually. Messages need a response and resources must be monitored—often over multiple systems and across platforms. How can you be sure you won’t miss important system events? Automate your message center with the Robot Message Management Solution. Key features include:

  • FORTRAThe thought of printing, distributing, and storing iSeries reports manually may reduce you to tears. Paper and labor costs associated with report generation can spiral out of control. Mountains of paper threaten to swamp your files. Robot automates report bursting, distribution, bundling, and archiving, and offers secure, selective online report viewing. Manage your reports with the Robot Report Management Solution. Key features include:

  • FORTRAFor over 30 years, Robot has been a leader in systems management for IBM i. With batch job creation and scheduling at its core, the Robot Job Scheduling Solution reduces the opportunity for human error and helps you maintain service levels, automating even the biggest, most complex runbooks. Manage your job schedule with the Robot Job Scheduling Solution. Key features include:

  • LANSA Business users want new applications now. Market and regulatory pressures require faster application updates and delivery into production. Your IBM i developers may be approaching retirement, and you see no sure way to fill their positions with experienced developers. In addition, you may be caught between maintaining your existing applications and the uncertainty of moving to something new.

  • LANSAWhen it comes to creating your business applications, there are hundreds of coding platforms and programming languages to choose from. These options range from very complex traditional programming languages to Low-Code platforms where sometimes no traditional coding experience is needed. Download our whitepaper, The Power of Writing Code in a Low-Code Solution, and:

  • LANSASupply Chain is becoming increasingly complex and unpredictable. From raw materials for manufacturing to food supply chains, the journey from source to production to delivery to consumers is marred with inefficiencies, manual processes, shortages, recalls, counterfeits, and scandals. In this webinar, we discuss how:

  • The MC Resource Centers bring you the widest selection of white papers, trial software, and on-demand webcasts for you to choose from. >> Review the list of White Papers, Trial Software or On-Demand Webcast at the MC Press Resource Center. >> Add the items to yru Cart and complet he checkout process and submit

  • Profound Logic Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application.

  • SB Profound WC 5536Join us for this hour-long webcast that will explore:

  • Fortra IT managers hoping to find new IBM i talent are discovering that the pool of experienced RPG programmers and operators or administrators with intimate knowledge of the operating system and the applications that run on it is small. This begs the question: How will you manage the platform that supports such a big part of your business? This guide offers strategies and software suggestions to help you plan IT staffing and resources and smooth the transition after your AS/400 talent retires. Read on to learn: