14.4.1 内存管理
尽管Java提供了自动垃圾回收,有时也想知道对象堆的大小以及它还剩下多少。可以利用这些信息检验你的代码的效率,或估计对某些类型,有多少对象可以被实例化。为了获得这些值,可以使用totalMemory( )和freeMemory( )方法。正如我们在第1部分提及的,Java的垃圾回收器周期性地运行将不再使用的对象放入回收站。然而有时想在收集器的下一个指定循环之前收集被丢弃的对象。可以通过调用gc( )方法按照要求运行垃圾回收器。一个好的尝试是调用gc( )方法,然后再调用freeMemory( )方法以获得内存使用的底线。接着执行你的程序,并再一次调用freeMemory( )方法看分配了多少内存。下面的例子说明了这个思想。
// 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());
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);
}
}
这个例子的一个输出样本如下(当然,你的实际运行结果可能会与之不同):
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
14.4.2 执行其他的程序
在可靠的环境中,可以在你的多任务操作系统中使用Java去执行其他特别繁重的进程(也即程序)。exec( )方法的几种形式允许命名想运行的程序以及它们的输入参数。exec( )方法返回一个Process对象,这个对象可以被用来控制你的Java程序如何与这个正在运行的新进程相互作用。因为Java可以运行在多种平台和多种操作系统的情况下,exec( )方法本质上是依赖于环境的。下面的例子使用exec( )方法装入Window的简单文本编辑器——notepad。显而易见,这个例子必须在Windows操作系统下运行。
// Demonstrate exec().
class ExecDemo {
public static void main(String args[]) {
Runtime r = Runtime.getRuntime();
Process p = null;
try {
p = r.exec("notepad");
} catch (Exception e) {
System.out.println("Error executing notepad.");
}
}
}
exec( )方法有几个形式可用,而在本例子中展示的是最常用的一种。在新程序开始运行之后,由exec( )方法返回的Process对象可以被Process方法使用。可以使用destroy( )方法杀死子进程。waitFor( )方法暂停你的程序直至子进程结束。当子进程结束后,exitValue( )方法返回子进程返回的值。如果没有问题发生,它通常返回0。下面是前面关于exec( )方法例子的改进版本。例子被修改为等待直至正在运行的进程退出:
// Wait until notepad is terminated.
class ExecDemoFini {
public static void main(String args[]) {
Runtime r = Runtime.getRuntime();
Process p = null;
try {
p = r.exec("notepad");
p.waitFor();
} catch (Exception e) {
System.out.println("Error executing notepad.");
}
System.out.println("Notepad returned " + p.exitValue());
}
}