`

Java并发实战-私有构造函数捕获

    博客分类:
  • JAVA
阅读更多
 java并发编程实战P58
私有构造函数捕获:私有构造函数进行线程安全地对象复制

转发:http://atbug.com/private-constructor-capture-idiom/

/**
 * 将拷贝构造函数实现为this(p.x, p.y),那么会产生竞态条件,而私有构造函数则可以避免这种竞态条件。这是私有构造函数捕获模式的一个实例 */
public class SafePoint {
    private int x, y;

//    私有内部构造函数
private SafePoint(int[] a) {
        this(a[0], a[1]);
    }

    public SafePoint(SafePoint p) {
//        线程安全的获取x、y坐标,避免x、y不一致产生数据竟态竞争
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;
    }
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics