`

JAVA Concurrency - SafePoint中的私有构造方法解释

 
阅读更多

 

卓二妹原创,转载请注明来源。

 

@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; 
    }
}

 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).

 

这里如果将private SafePoint(int[] a) { this(a[0], a[1]); }方法改为public就会有race condition问题。为什么呢?

 

因为如果我们要复制一个SafePoint对象时,我们会首先想到编写下面这样一个方法:

 

 public SafePoint(SafePoint safePoint){
     this(safePoint.x, safePoint.y);
 }

 

但是当我们在通过复制originalSafePoint创建新的SafePoint对象时,可能有一个线程正在调用originalSafePoint.setXY方法,导致读取safePoint.x, safePoint.y这对值可能一个更新了而一个没更新,出现线程不安全。因此x,y必须同时读取出来。所以在复制的时候,不能像上面那样调用,而要用getXY()把x y一起取出来。

 

 

 public SafePoint(SafePoint safePoint){
     int [] xy = safePoint.getXY();
     this(xy[0], xy[1]);
 }

 上面的代码会有编译错误,因为this()必须是body的第一行:


 

 

那么好吧,那我们这样写就行了是吗?

 

    public SafePoint(SafePoint originalSafePoint){
        this(originalSafePoint.getXY()[0],originalSafePoint.getXY()[1]);
    }

 

 

显然这样也是有问题的,因为originalSafePoint.getXY()被调用了两次,这时候两次取出来的x y已经不是一对值了。

 

因此我们只有提供一个构造方法接受getXY()返回的数组作为参数,来复制一个对象:

 

public SafePoint(SafePoint originalSafePoint){
    this(originalSafePoint.getXY());
}
private SafePoint(int [] xy){
    this(xy[0], xy[1]);
}

 

 

这样就避免了上面的copy constructor的问题。现在再来读一下作者说的这句话就清楚很多了:

写道
The private constructor exists to avoid the race condition that would occur if the copy constructor were implemented as this(p.x, p.y);

 私有的构造方法的存在,是为了避免在复制构造函数(即SafePoint(SafePoint originalSafePoint))的中因调用this(p.x, p.y)而引起的race condition。

 

 

 

  • 大小: 68.9 KB
分享到:
评论

相关推荐

    Java-concurrency-master.zip

    `Java-concurrency-master`中的资料可能包括教程、代码示例、最佳实践等内容,对提升并发编程技能非常有益。如果你深入研究这些资源,将能够更好地掌握Java并发编程的核心概念和技术,从而在实际开发中编写出高效、...

    Java-Concurrency-Essentials

    Concurrency is always a challenge for developers and writing concurrent programs can be extremely hard. There is a number of things that could potentially blow up and the complexity of systems rises ...

    Node.js-concurrency-loggerHTTP日志中间件

    通过查看这个文件,开发者可以直接在本地环境中安装和测试`concurrency-logger`,以便于定制或扩展功能。 总结一下,`Node.js-concurrency-loggerHTTP日志中间件`是一个强大的开发工具,它可以帮助开发者监控HTTP...

    Java-Concurrency-in-Practice.rar

    - **Java线程API**:讲解了Java中的Thread类和Runnable接口,以及如何创建和管理线程。 - **同步机制**:包括synchronized关键字、wait/notify机制,以及如何避免竞态条件和死锁。 2. **并发工具类** - **...

    Android代码-java-concurrency-patterns

    Java Concurrency Patterns and Features Concurrency Patterns and features found in Java, through multithreaded programming. Features: Threads and Runnables Locks Intrinsic Explicit Reentrant Read...

    CPP-Concurrency-In-Action-2ed-2019-master.zip

    3. **原子操作与内存模型**:解释C++的内存模型,以及std::atomic的用法,保证多线程环境下的数据一致性。 4. **条件变量**:讲解std::condition_variable和std::condition_variable_any的用法,实现线程间的同步...

    java_concurrency_in_practice_source源代码

    这里的"java_concurrency_in_practice_source"源代码正是书中实例的实现,它涵盖了Java多线程编程中的关键概念和技术。 1. **线程基础**:Java中创建线程有两种方式,一是通过`Thread`类的子类,二是实现`Runnable`...

    Python库 | oslo.concurrency-4.0.2-py3-none-any.whl

    资源分类:Python库 所属语言:Python 资源全名:oslo.concurrency-4.0.2-py3-none-any.whl 资源来源:官方 安装方法:https://lanzao.blog.csdn.net/article/details/101784059

    Java Concurrency in Practice 无水印pdf

    Java Concurrency in Practice 英文无水印pdf pdf所有页面使用FoxitReader和PDF-XChangeViewer测试都可以打开 本资源转载自网络,如有侵权,请联系上传者或csdn删除 本资源转载自网络,如有侵权,请联系上传者...

    Java Concurrency in Practice JAVA并发编程实践(中英文版)

    Using the concurrency building blocks in java.util.concurrent Performance optimization dos and don'ts Testing concurrent programs Advanced topics such as atomic variables, nonblocking algorithms, ...

    Python库 | django-concurrency-0.4.tar.gz

    资源分类:Python库 所属语言:Python 资源全名:django-concurrency-0.4.tar.gz 资源来源:官方 安装方法:https://lanzao.blog.csdn.net/article/details/101784059

    开源项目-kevchn-go-concurrency-patterns.zip

    开源项目-kevchn-go-concurrency-patterns.zip,Implementations of Golang Concurrency Patterns from Rob Pike's 2012 Talk

    Python库 | oslo.concurrency-3.15.0-py2.py3-none-any.whl

    资源分类:Python库 所属语言:Python 资源全名:oslo.concurrency-3.15.0-py2.py3-none-any.whl 资源来源:官方 安装方法:https://lanzao.blog.csdn.net/article/details/101784059

    Java 9 Concurrency Cookbook - Second Edition

    Java 9 Concurrency Cookbook - Second Edition by Javier Fernandez Gonzalez English | 25 Apr. 2017 | ASIN: B01KOG6V5M | 594 Pages | AZW3 | 4.11 MB Key Features Get detailed coverage of important ...

    南开大学数据库原理课件lecture9-Concurrency-Control.ppt

    南开大学数据库原理课件lecture9-Concurrency-Control.ppt

    java-concurrency-in-practice-exercises:看书时的一些练习

    《Java并发编程实践》是Java并发编程领域的一本经典之作,由Brian Goetz等多位...这个"java-concurrency-in-practice-exercises-master"项目可能包含了书中各个章节的实战代码,是检验和巩固理论知识的良好实践资源。

    the-art-of-java-concurrency-programming:Java并发编程的艺术原始代码

    压缩包文件"the-art-of-java-concurrency-programming-master"包含了该书中的源代码示例,这对于学习和实践书中理论提供了宝贵的资源。 在Java并发编程中,有几个核心概念和技术是必须掌握的: 1. **线程**:线程...

    Core Java Volume II 最新第8版 part1全两卷 (附随书源码)

    Fully updated for the new Java SE 6 platform, this no-nonsense tutorial and reliable reference illuminates the most important language and library features with thoroughly tested real-world examples....

    Java并发编程实践(java concurrency in practice)pdf (java多线程总结.ppt)

    《Java并发编程实践》是Java开发者必读的经典之作,由Brian Goetz等多位专家共同撰写。这本书深入浅出地探讨了Java平台上的并发问题,帮助读者理解和掌握如何编写高效、可靠且可维护的多线程应用程序。以下是该书...

Global site tag (gtag.js) - Google Analytics