Java对象生命周期管理:终结器、垃圾回收与初始化器详解
立即解锁
发布时间: 2025-08-17 02:35:34 阅读量: 12 订阅数: 22 


Java编程基础与SCJP认证指南
### Java对象生命周期管理:终结器、垃圾回收与初始化器详解
#### 1. 终结器链
在Java中,枚举类型不能声明终结器,这意味着枚举常量永远不会被终结。与子类构造函数不同,重写的终结器不会隐式链接。因此,子类中的终结器应在最后显式调用其父类的终结器。
以下是一个示例代码,展示了终结器链的使用:
```java
class BasicBlob {
static int idCounter;
static int population;
protected int blobId;
BasicBlob() {
blobId = idCounter++;
++population;
}
protected void finalize() throws Throwable {
--population;
super.finalize();
}
}
class Blob extends BasicBlob {
int[] size;
Blob(int bloatedness) {
size = new int[bloatedness];
System.out.println(blobId + ": Hello");
}
protected void finalize() throws Throwable {
System.out.println(blobId + ": Bye");
super.finalize();
}
}
public class Finalizers {
public static void main(String[] args) {
int blobsRequired, blobSize;
try {
blobsRequired = Integer.parseInt(args[0]);
blobSize = Integer.parseInt(args[1]);
} catch(IndexOutOfBoundsException e) {
System.err.println("Usage: Finalizers <number of blobs> <blob size>");
return;
}
for (int i = 0; i < blobsRequired; ++i) {
new Blob(blobSize);
}
System.out.println(BasicBlob.population + " blobs alive");
}
}
```
运行命令 `java Finalizers 5 500000` 后,输出结果如下:
```
0: Hello
1: Hello
2: Hello
0: Bye
1: Bye
2: Bye
3: Hello
4: Hello
2 blobs alive
```
从输出结果可以看出,在创建5个 `Blob` 对象的过程中,有3个对象在所有对象创建完成之前就被垃圾回收了。
#### 2. 编程式调用垃圾回收
Java提供了显式调用垃圾回收的方法,但不能保证垃圾回收一定会执行。程序只能请求进行垃圾回收,而无法强制其执行。可以使用 `System.gc()` 方法请求垃圾回收,使用 `System.runFinalization()` 方法建议对符合垃圾回收条件的对象运行任何挂起的终结器。
以下是一个示例代码,展示了如何编程式调用垃圾回收:
```java
class BasicBlob { /* See Example 9.2. */ }
class Blob extends BasicBlob { /* See Example 9.2.*/ }
public class MemoryCheck {
public static void main(String[] args) {
int blobsRequired, blobSize;
try {
blobsRequired = Integer.parseInt(args[0]);
blobSize = Integer.parseInt(args[1]);
} catch(IndexOutOfBoundsException e) {
System.err.println("Usage: MemoryCheck <number of blobs> <blob size>");
return;
}
Runtime environment = Runtime.getRuntime();
System.out.println("Total memory: " + environment.totalMemory());
System.out.println("Free memory before blob creation: " + environment.freeMemory());
for (int i = 0; i < blobsRequired; ++i) {
new Blob(blobSize);
}
System.out.println("Free memory after blob creation: " + environment.freeMemory());
System.gc();
System.out.println("Free memory after requesting GC: " + environment.freeMemory());
System.out.println(BasicBlob.population + " blobs alive");
}
}
```
运行命令 `java MemoryCheck 5 100000` 后,输出结果如下:
```
Total memory: 2031616
Free memory before blob creation: 1773192
0: Hello
1: Hello
2: Hello
1: Bye
2: Bye
3: Hello
0: Bye
3: Bye
4: Hello
Free memory after blob creation: 818760
4: Bye
Free memory after requesting GC: 1619656
0 blobs alive
```
从输出结果可以看出,在请求垃圾回收后,可用内存增加了,说明垃圾回收请求被执行了。
#### 3. 自动垃圾回收的注意事项
- **终结器执行无保证**:符合垃圾回收条件的对象不一定会
0
0
复制全文
相关推荐










