Let’s look at two of the most common uses of theRuntimeclass: memory management
and executing additional processes.
Memory Management
Although Java provides automatic garbage collection, sometimes you will want to know
how large the object heap is and how much of it is left. You can use this information, for
example, to check your code for efficiency or to approximate how many more objects
of a certain type can be instantiated. To obtain these values, use thetotalMemory( )and
freeMemory( )methods.
As mentioned in Part I, Java’s garbage collector runs periodically to recycle unused objects.
However, sometimes you will want to collect discarded objects prior to the collector ’s next
appointed rounds. You can run the garbage collector on demand by calling thegc( )method.
A good thing to try is to callgc( )and then callfreeMemory( )to get a baseline memory usage.
Next, execute your code and callfreeMemory( )again to see how much memory it is allocating.
The following program illustrates this idea:
// Demonstrate totalMemory(), freeMemory() and gc().
class MemoryDemo {
public static void main(String args[]) {
Runtime r = Runtime.getRuntime();
long mem1, mem2;
Integer someints[] = new Integer[1000];
System.out.println("Total memory is: " +
r.totalMemory());
Chapter 16: Exploring java.lang 405
Method Description
boolean
removeShutdownHook(Threadthrd)
Removesthrdfrom the list of threads to run when
the Java Virtual Machine terminates. It returnstrueif
successful—that is, if the thread was removed.
void runFinalization( ) Initiates calls to thefinalize( )methods of unused but
not yet recycled objects.
long totalMemor y( ) Returns the total number of bytes of memor y available
to the program.
void traceInstructions(booleantraceOn) Turns on or off instruction tracing, depending upon
the value oftraceOn.IftraceOnistrue, the trace is
displayed. If it isfalse, tracing is turned off.
void traceMethodCalls(booleantraceOn) Turns on or off method call tracing, depending upon
the value oftraceOn.IftraceOnistrue, the trace is
displayed. If it isfalse, tracing is turned off.
TABLE 16-11 A Sampling of Methods Defined byRuntime(continued)