jimmy 發問時間: 電腦與網際網路程式設計 · 10 年前

immutable object是什麼意思

"String"is an immutable object in Java language;explain what is " immutable object"?

1 個解答

評分
  • 10 年前
    最佳解答

    Immutable object 是指當一個類別被實體化(新物件)後,它的狀態將無法即無法再被更改.

    String就是一個 immutable object . 請看以下例子 String s = new String("Hello");

    s = s + " Java"; 在第一行後, 變數s的記憶體位置指向疊堆裡新創的一個物件叫"Hello". 第二後過後, 原本的"Hello"值並非更新為" Hello Java", 而是在疊堆裡又新建立一個物件叫"Hello Java",然後s的指標從新指向這個新的物件.參考 "An object is considered immutable if its state cannot change after it is constructed. Maximum reliance on immutable objects is widely accepted as a sound strategy for creating simple, reliable code."Immutable object通常也能確保執行緒安全. 例如一個簡單範例的class:

    public class Coord{

    private int x, y;

    public Coord(int x, int y){

    this.x = x;

    this.y = y;

    }

    public int getX(){ return this.x;}

    public int getY(){ return this.y;}

    public void update(int a, int b){

    this.x += a;

    this.y += b;

    }

    }

    上述的class看似沒甚麼問題, 不過當有兩個執行緒同時在使用setCoord()進行寫入的動作時,則無法保證得到的結果會是如何. 也許可以為這個方法加上同步安全機制,但也比較麻煩. 換一個角度想想,如果這時回傳的是:

    public Coord update(int a, int b){

    return Coord(this.x+a, this.y+b);

    }

    由於每次回傳的都是一個新的Coord物件, 並沒有做更新(寫)的動作, 沒有寫入就不需要同步,因此能確保執行緒安全

    參考"Immutable objects are particularly useful in concurrent applications. Since they cannot change state, they cannot be corrupted by thread interference or observed in an inconsistent state."

    一個immutable object通常沒有一個public的set方法, 通常他們比較像ReadOnly的形態.

    好處上述以提過了,但同時也有人評論大量使用的這類型的類別會吃掉許多資源,因為在每次的更新中都會重新創造新的物件. 但其實使用immutable object的同時,也省下您必須在執行緒安全上必須多寫的程式碼,加上更頻繁的垃圾處理機制能幫助你清理回收多餘的資源.

    參考"Programmers are often reluctant to employ immutable objects, because they worry about the cost of creating a new object as opposed to updating an object in place. The impact of object creation is often overestimated, and can be offset by some of the efficiencies associated with immutable objects. These include decreased overhead due to garbage collection, and the elimination of code needed to protect mutable objects from corruption."

還有問題?馬上發問,尋求解答。