Monday 13 March 2017

strictfp, Native Methods & Using assert - Java Tutorials

strictfp

Java 2 added a new keyword to the Java language, called strictfp. With the creation of Java 2, the floating point computation model was relaxed slightly to make certain floating point computations faster for certain processors, such as the Pentium. Specifically, the new model does not require the truncation of certain intermediate values that occur during a computation. By modifying a class or a method with strictfp, you ensure that floating point calculations (and thus all truncations) take place precisely as they did in earlier versions of Java. The truncation affects only the exponent of certain operations. When a class is modified by strictfp, all the methods in the class are also modified by strictfp automatically.

For example, the following fragment tells Java to use the original floating point model for calculations in all methods defined within MyClass:

strictfp class MyClass { //...

Frankly, most programmers never need to use strictfp, because it affects only a very small class of problems.




Native Methods

Although it is rare, occasionally, you may want to call a subroutine that is written in a language other than Java. Typically, such a subroutine exists as executable code for the CPU and environment in which you are working—that is, native code. For example, you may want to call a native code subroutine to achieve faster execution time. Or, you may want to use a specialized, third-party library, such as a statistical package.

However, because Java programs are compiled to bytecode, which is then interpreted (or compiled on-the-fly) by the Java run-time system, it would seem impossible to call a native code subroutine from within your Java program. Fortunately, this conclusion is false. Java provides the native keyword, which is used to declare native code methods. Once declared, these methods can be called from inside your Java program just as you call any other Java method.

To declare a native method, precede the method with the native modifier, but do not define any body for the method. For example:

  public native int meth() ;

After you declare a native method, you must write the native method and follow a rather complex series of steps to link it with your Java code.

Most native methods are written in C. The mechanism used to integrate C code with a Java program is called the Java Native Interface (JNI). This methodology was created by Java 1.1 and then expanded and enhanced by Java 2. (Java 1.0 used a different approach, which is now completely outdated.) A detailed description of the JNI is beyond the scope of this book, but the following description provides sufficient information for most applications.

The precise steps that you need to follow will vary between different Java environments and versions. This also depends on the language that you are using to implement the native method. The following discussion assumes a Windows 95/98/XP/NT/2000 environment. The language used to implement the native method is C.

The easiest way to understand the process is to work through an example. To begin, enter the following short program, which uses a native method called test( ):

  // A simple example that uses a native method.
  public class NativeDemo {
    int i;
    public static void main(String args[]) {
      NativeDemo ob = new NativeDemo();

      ob.i = 10;
      System.out.println("This is ob.i before the native method:" +
                          ob.i);
      ob.test(); // call a native method
      System.out.println("This is ob.i after the native method:" +
                          ob.i);
    }

    // declare native method
    public native void test() ;

    // load DLL that contains static method
    static {
      System.loadLibrary("NativeDemo");
    }
  }

Notice that the test( ) method is declared as native and has no body. This is the method that we will implement in C shortly. Also notice the static block. As explained earlier in this book, a static block is executed only once, when your program begins execution (or, more precisely, when its class is first loaded). In this case, it is used to load the dynamic link library that contains the native implementation of test( ). (You will see how to create this library soon.)

The library is loaded by the loadLibrary( ) method, which is part of the System class. This is its general form:

      static void loadLibrary(String filename)

Here, filename is a string that specifies the name of the file that holds the library. For the Windows environment, this file is assumed to have the .DLL extension.

After you enter the program, compile it to produce NativeDemo.class. Next, you must use javah.exe to produce one file: NativeDemo.h. (javah.exe is included in the SDK.) You will include NativeDemo.h in your implementation of test( ). To produce NativeDemo.h, use the following command:

      javah -jni NativeDemo

This command produces a header file called NativeDemo.h. This file must be included in the C file that implements test( ). The output produced by this command is shown here:

  /* DO NOT EDIT THIS FILE - it is machine generated */
  #include <jni.h>
  /* Header for class NativeDemo */

  #ifndef _Included_NativeDemo
  #define _Included_NativeDemo
  #ifdef _ _cplusplus
  extern "C" {
  #endif
  /*
   * Class: NativeDemo
   * Method: test
   * Signature: ()V
   */
  JNIEXPORT void JNICALL Java_NativeDemo_test
   (JNIEnv *, jobject);

  #ifdef _ _cplusplus
  }
  #endif
  #endif

Pay special attention to the following line, which defines the prototype for the test( ) function that you will create:

  JNIEXPORT void JNICALL Java_NativeDemo_test(JNIEnv *, jobject);

Notice that the name of the function is Java_NativeDemo_test( ). You must use this as the name of the native function that you implement. That is, instead of creating a C function called test( ), you will create one called Java_NativeDemo_test( ). The NativeDemo component of the prefix is added because it identifies the test( ) method as being part of the NativeDemo class. Remember, another class may define its own native test( ) method that is completely different from the one declared by NativeDemo. Including the class name in the prefix provides a way to differentiate between differing versions. As a general rule, native functions will be given a name whose prefix includes the name of the class in which they are declared.

After producing the necessary header file, you can write your implementation of test( ) and store it in a file named NativeDemo.c:

  /* This file contains the C version of the
     test() method.
  */

  #include <jni.h>
  #include "NativeDemo.h"
  #include <stdio.h>

  JNIEXPORT void JNICALL Java_NativeDemo_test(JNIEnv *env, jobject                                                 obj)
  {

    jclass cls;
    jfieldID fid;
    jint i;

    printf("Starting the native method.\n");
    cls = (*env)->GetObjectClass(env, obj);
    fid = (*env)->GetFieldID(env, cls, "i", "I");

    if(fid == 0) {
      printf("Could not get field id.\n");
      return;
    }
    i = (*env)->GetIntField(env, obj, fid);
    printf("i = %d\n", i);
    (*env)->SetIntField(env, obj, fid, 2*i);
    printf("Ending the native method.\n");
  }

Notice that this file includes jni.h, which contains interfacing information. This file is provided by your Java compiler. The header file NativeDemo.h was created by javah, earlier.

In this function, the GetObjectClass( ) method is used to obtain a C structure that has information about the class NativeDemo. The GetFieldID( ) method returns a C structure with information about the field named “i” for the class. GetIntField( ) retrieves the original value of that field. SetIntField( ) stores an updated value in that field. (See the file jni.h for additional methods that handle other types of data.)

After creating NativeDemo.c, you must compile it and create a DLL. To do this by using the Microsoft C/C++ compiler, use the following command line. (You might need to specifiy the path to jni.h and its subordinate file jni_md.h.)

      Cl /LD NativeDemo.c

This produces a file called NativeDemo.dll. Once this is done, you can execute the Java program, which will produce the following output:

  This is ob.i before the native method: 10
  Starting the native method.
  i = 10
  Ending the native method.
  This is ob.i after the native method: 20

The specifics surrounding the use of native are implementation- and environmentdependent. Furthermore, the specific manner in which you interface to Java code is subject to change. You must consult the documentation that accompanies your Java development system for details on native methods.


Problems with Native Methods

Native methods seem to offer great promise, because they enable you to gain access to your existing base of library routines, and they offer the possibility of faster run-time execution. But native methods also introduce two significant problems:
  • Potential security risk Because a native method executes actual machine code, it can gain access to any part of the host system. That is, native code is not confined to the Java execution environment. This could allow a virus infection, for example. For this reason, applets cannot use native methods. Also, the loading of DLLs can be restricted, and their loading is subject to the approval of the security manager.
  • Loss of portability Because the native code is contained in a DLL, it must be present on the machine that is executing the Java program. Further, because each native method is CPU- and operating-system-dependent, each DLL is inherently nonportable. Thus, a Java application that uses native methods will be able to run only on a machine for which a compatible DLL has been installed. The use of native methods should be restricted, because they render your Java programs nonportable and pose significant security risks.





Using assert

Java 2, version 1.4 added a new keyword to Java: assert. It is used during program development to create an assertion, which is a condition that should be true during the execution of the program. For example, you might have a method that should always return a positive integer value. You might test this by asserting that the return value is greater than zero using an assert statement. At run time, if the condition actually is true, no other action takes place. However, if the condition is false, then an AssertionError is thrown. Assertions are often used during testing to verify that some expected condition is actually met. They are not usually used for released code.

The assert keyword has two forms. The first is shown here.

      assert condition;

Here, condition is an expression that must evaluate to a Boolean result. If the result is true, then the assertion is true and no other action takes place. If the condition is false, then the assertion fails and a default AssertionError object is thrown. The second form of assert is shown here.

      assert condition : expr;

In this version, expr is a value that is passed to the AssertionError constructor. This value is converted to its string format and displayed if an assertion fails. Typically, you will specify a string for expr, but any non-void expression is allowed as long as it defines a reasonable string conversion.

Here is an example that uses assert. It verifies that the return value of getnum( ) is positive.

  // Demonstrate assert.
  class AssertDemo {
    static int val = 3;

    // Return an integer.
    static int getnum() {
      return val--;
    }

    public static void main(String args[])
    {
      int n;

      for(int i=0; i < 10; i++) {
        n = getnum();

        assert n > 0; // will fail when n is 0
        
        System.out.println("n is " + n);
      }
    }
  }

Programs that use assert must be compiled using the -source 1.4 option. For example, to compile the preceding program, use this line:

  javac -source 1.4 AssertDemo.java

To enable assertion checking at run time, you must specify the -ea option. For example, to enable assertions for AssertDemo, execute it using this line.

  java -ea AssertDemo

After compiling and running as just described, the program creates the following output.

  n is 3
  n is 2
  n is 1
  Exception in thread "main" java.lang.AssertionError
          at AssertDemo.main(AssertDemo.java:17)

In main( ), repeated calls are made to the method getnum( ), which returns an integer value. The return value of getnum( ) is assigned to n and then tested using this assert statement.

  assert n > 0; // will fail when n is 0

This statement will fail when n equals 0, which it will after the fourth call. When this happens, an exception is thrown.

As explained, you can specify the message displayed when an assertion fails. For example, if you substitute

  assert n > 0 : "n is negative!";

for the assertion in the preceding program, then the following ouptut will be generated.

 n is 3
 n is 2
 n is 1
 Exception in thread "main" java.lang.AssertionError: n is negative!
        at AssertDemo.main(AssertDemo.java:17)

One important point to understand about assertions is that you must not rely on them to perform any action actually required by the program. The reason is that normally, released code will be run with assertions disabled. For example, consider this variation of the preceding program.

  // A poor way to use assert!!!
  class AssertDemo {
    // get a random number generator
    static int val = 3;

    // Return an integer.
    static int getnum() {
      return val--;
    }

    public static void main(String args[])
    {
      int n = 0;

      for(int i=0; i < 10; i++) {

        assert (n = getnum()) > 0; // This is not a good idea!

        System.out.println("n is " + n);
      }
    }
  }

In this version of the program, the call to getnum( ) is moved inside the assert statement. Although this works fine if assertions are enabled, it will cause a malfunction when assertions are disabled because the call to getnum( ) will never be executed! In fact, n must now be initialized, because the compiler will recognize that it might not be assigned a value by the assert statement.

Assertions are a good addition to Java because they streamline the type of error checking that is common during development. For example, prior to assert, if you wanted to verify that n was positive in the preceding program, you had to use a sequence of code similar to this:

  if(n < 0) {
    System.out.println("n is negative!");
    return; // or throw an exception
  }

With assert, you need only one line of code. Furthermore, you don’t have to remove the assert statements from your released code.


Assertion Enabling and Disabling Options

When executing code, you can disable assertions by using the -da option. You can enable or disable a specific package by specifying its name after the -ea or -da option. For example, to enable assertions in a package called MyPack, use

  -ea:MyPack

To disable assertions in MyPack use

  -da:MyPack

To enable or disable all subpackages of a package, follow the package name with three dots. For example,

  -ea:MyPack...

You can also specify a class with the -ea or -da option. For example, this enables AssertDemo individually.

  -ea:AssertDemo

No comments:

Post a Comment