首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

確保 Java 物件正確清理:finally 區塊與明確清理模式

     編輯:Java 相關知識

無解構子的語言設計

Java 沒有 C++ 風格的「解構子」。C++ 物件銷毀時自動呼叫解構子,Java 則仰賴垃圾收集器自動回收記憶體。但某些類別在生命週期中執行的動作(如檔案、圖形資源、網路連線)需要明確清理,垃圾收集器的不可預測性使我們必須自行編寫清理方法,並由用戶端在 finally 區塊中呼叫。

CAD 系統範例:Shape 體系的清理鏈

//: CADSystem.java
import java.util.*;

class Shape {
    Shape(int i) { System.out.println("Shape constructor"); }
    void cleanup() { System.out.println("Shape cleanup"); }
}
class Circle extends Shape {
    Circle(int i) { super(i); System.out.println("Drawing a Circle"); }
    void cleanup() { System.out.println("Erasing a Circle"); super.cleanup(); }
}
class Triangle extends Shape {
    Triangle(int i) { super(i); System.out.println("Drawing a Triangle"); }
    void cleanup() { System.out.println("Erasing a Triangle"); super.cleanup(); }
}
class Line extends Shape {
    private int start, end;
    Line(int start, int end) { super(start); this.start=start; this.end=end; System.out.println("Drawing a Line: "+start+", "+end); }
    void cleanup() { System.out.println("Erasing a Line: "+start+", "+end); super.cleanup(); }
}

public class CADSystem extends Shape {
    private Circle c; private Triangle t; private Line[] lines = new Line[10];
    CADSystem(int i) {
        super(i+1);
        for(int j=0;j<10;j++) lines[j]=new Line(j,j*j);
        c=new Circle(1); t=new Triangle(1);
        System.out.println("Combined constructor");
    }
    void cleanup() {
        System.out.println("CADSystem.cleanup()");
        t.cleanup(); c.cleanup();
        for(int i=0;i

關鍵要點

  • 所有清理方法需呼叫 super.cleanup() 確保基底類別資源釋放
  • try-finally 保證清理碼必定執行,無論是否拋出例外
  • 清理順序:先處理衍生類別特有資源,再呼叫基底類別清理(模仿 C++ 解構子順序)
  • 垃圾收集器不保證呼叫 finalize(),切勿依賴它進行非記憶體資源清理
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved