THE Java™ Programming Language, Fourth Edition

(Jeff_L) #1

You have already learned about the first four of these areas (you learned about interacting with the garbage
collector via the gc and runFinalization methods in Chapter 17, on page 452, and about
availableProcessors in Chapter 14 on page 359). Now is the time to cover the final two.


23.4.1. Loading Native Code


In Chapter 2, you learned about the native modifier (see page 74) that can be applied to methods and which
signifies that the method's implementation is being provided by native code. At runtime the native code for
such methods must be loaded into the virtual machine so that the methods can be executed. The details of this
process are system-dependent, but two methods in Runtime allow this activity to occur:


public voidloadLibrary(String libname)

Loads the dynamic library with the specified library name. The library
corresponds to a file in the local file system that is located in some place
where the system knows to look for library files. The actual mapping from
the library name to a file name is system-dependent.

public voidload(String filename)

Loads the file specified by filename as a dynamic library. In contrast with
loadLibrary, load allows the library file to be located anywhere in the
file system.

Typically, classes that have native methods load the corresponding library as part of the initialization of the
class by placing the load invocation in a static initialization block. However, the library could be lazily
loaded when an actual invocation of the method occurs.


Loading native code libraries is, naturally, a privileged operation, and you will get a SecurityException
if you do not have the required permissions. If the library cannot be found or if an error occurs while the
system tries to load the library, an UnsatisfiedLinkError is thrown.


A related method in class SystemmapLibraryNamemaps a library name into a system-dependent library
name. For example, the library name "awt" might map to "awt.dll" under Windows, while under UNIX
it might map to "libawt.so".


23.4.2. Debugging


Two methods in Runtime support the debugging of applications:


public voidTRaceInstructions(boolean on)

Enables or disables the tracing of instructions depending on the value of on.
If on is TRue, this method suggests that the virtual machine emit debugging
information for each instruction as it is executed.

public voidtraceMethodCalls(boolean on)

Enables or disables the tracing of method calls depending on the value of on.
If on is true, this method suggests that the virtual machine emit debugging
information for each method when it is called.
Free download pdf