home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam  


Book Home Java Servlet Programming Search this book

13.5. Using Native Methods

Despite Sun's push for 100% Pure Java, native code still has its place. You need native code to do things that Java (and external programs launched by Java) cannot do: locking files, accessing user IDs, accessing shared memory, sending faxes, and so on. Native code is also useful when accessing legacy data through non-Java gateways. Last, in situations where every last bit of performance is vital, native code libraries can give a servlet a big boost.

Native code, however, should not be used except when absolutely necessary, since if the native code run by a servlet goes south, the entire server goes down with it! The security protections in Java can't protect the server from native code crashes. For this reason, it's wise not to use the native JDBC-ODBC bridge from a servlet because many ODBC drivers seem to have problems with multithreaded access. Native code also limits the platform independence of a servlet. While this may not matter for custom-built servlets tied to a particular server, it's something to remember.

How a servlet accesses native methods depends on the web server and JVM in which it's running. To take a risk and speak in broad generalities, let us say that you can pretty much expect your web server and JVM to support the standard Java Native Interface (JNI). Using JNI is fairly involved, and even a basic introduction extends beyond the scope of this chapter. For a tutorial on JNI, see the upcoming Java Native Methods, by Alligator Descartes (O'Reilly).

When using JNI with servlets, remember these things:

  • Only the most liberal server security managers allow a servlet to execute native code.

  • There is a common JVM bug that doesn't allow native code to be loaded by a class that was loaded with a custom class loader (such as the class loader that loads servlets from the default servlet directory). Servlets using native code may therefore need to reside in the server's classpath (server_root/classes).

  • The directory where the shared library (or dynamic load library or DLL) that contains the native code is placed depends on the web server and JVM. Some servers have specific locations where they look for shared libraries. For example, the Java Web Server looks in server_root\lib on Windows and server_root/lib/sparc/solaris on Solaris. If the server doesn't provide a specific shared library directory, try placing the library in a JVM-specific location such as jdk_root\bin or under jdk_root/lib, or try an operating system-specific location such as windows_root\system32 or /usr/lib.



Library Navigation Links

Copyright © 2001 O'Reilly & Associates. All rights reserved.