2012-07-09 100 views
0

例如,複製構造函數是否需要複製互斥量?

public Foo{ 
    private Object mutex = new Object(); 
    private int bar; 

    public Foo(Foo f){ 
     this.mutex = f.getMutex(); 
     this.bar = f.getBar(); 
    } 

    public Object getMutex(){ 
     return mutex; 
    } 

    public void setBar(int bar){ 
     synchronized(mutex){ 
      this.bar = bar; 
     } 
    } 

    public int getBar(){ 
     synchronized(mutex){ 
      return bar; 
     } 
    } 
} 
+0

什麼是f('f.getMutex()')? – 2012-07-09 18:50:02

+1

取決於你想讓這個類表現如何,但絕對要讓這個互斥量數據成員最終。 – wolfcastle 2012-07-09 18:52:30

回答

3

這取決於 - 你想兩個對象共享一個互斥體(淺拷貝,真的),或者你想他們是獨立的?在大多數情況下,我希望後者,在這種情況下,你不會想要複製的參考。

1

在這種情況下,應該做以下所有的:

  1. 使互斥final
  2. 複製過程中不可複製的互斥
  3. 鎖定在原始實例的互斥。