最新文章

私有构造函数捕获模式

私有构造函数捕获模式

《Java并发编程实践》的注解中有提到这一概念。

The private constructor exists to avoid the race condition that would occur if the copy constructor were implemented as this (p.x, p.y); this is an example of the private constructor capture idiom (Bloch and Gafter, 2005).

结合原文代码:

@ThreadSafe
public class SafePoint{
    @GuardedBy("this") private int x,y;
  
    private SafePoint (int [] a) { this (a[0], a[1]); }
  
    public SafePoint(SafePoint p) { this (p.get()); }
  
    public SafePoint(int x, int y){
          this.x = x;
          this.y = y;
    }
  
    public synchronized int[] get(){
          return new int[] {x,y};
    }
  
    public synchronized void set(int x, int y){
          this.x = x;
          this.y = y;
    }
}

这里的构造器public SafePoint(SafePoint p) { this (p.get()); }是为了捕获另一个实例的状态。get()方法是一个同步方法,为了避免竞态没有分别提供x、y的公有getter方法。