Java The Complete Reference, Seventh Edition

(Greg DeLong) #1

406 Part II: The Java Library


mem1 = r.freeMemory();
System.out.println("Initial free memory: " + mem1);
r.gc();
mem1 = r.freeMemory();
System.out.println("Free memory after garbage collection: "
+ mem1);

for(int i=0; i<1000; i++)
someints[i] = new Integer(i); // allocate integers

mem2 = r.freeMemory();
System.out.println("Free memory after allocation: "
+ mem2);
System.out.println("Memory used by allocation: "
+ (mem1-mem2));

// discard Integers
for(int i=0; i<1000; i++) someints[i] = null;

r.gc(); // request garbage collection

mem2 = r.freeMemory();
System.out.println("Free memory after collecting" +
" discarded Integers: " + mem2);

}
}

Sample output from this program is shown here (of course, your actual results may vary):

Total memory is: 1048568
Initial free memory: 751392
Free memory after garbage collection: 841424
Free memory after allocation: 824000
Memory used by allocation: 17424
Free memory after collecting discarded Integers: 842640

Executing Other Programs


In safe environments, you can use Java to execute other heavyweight processes (that is,
programs) on your multitasking operating system. Several forms of theexec( )method
allow you to name the program you want to run as well as its input parameters. Theexec( )
method returns aProcessobject, which can then be used to control how your Java program
interacts with this new running process. Because Java can run on a variety of platforms and
under a variety of operating systems,exec( )is inherently environment-dependent.
The following example usesexec( )to launchnotepad, Windows’ simple text editor.
Obviously, this example must be run under the Windows operating system.

// Demonstrate exec().
class ExecDemo {
public static void main(String args[]) {
Runtime r = Runtime.getRuntime();
Process p = null;
Free download pdf