multithreading - 构造函数中的过早泄漏

标签 multithreading constructor synchronization

Java 文档声明了以下关于构造函数同步的内容:

Note that constructors cannot be synchronized — using the synchronized keyword with a constructor is a syntax error. Synchronizing constructors doesn't make sense, because only the thread that creates an object should have access to it while it is being constructed.

Warning: When constructing an object that will be shared between threads, be very careful that a reference to the object does not "leak" prematurely. For example, suppose you want to maintain a List called instances containing every instance of class. You might be tempted to add the following line to your constructor: instances.add(this); But then other threads can use instances to access the object before construction of the object is complete.

我无法理解整个街区。首先,它声明只有创建对象的线程才能访问构造函数。然后它警告过早泄漏,如果其他线程在构造完成之前访问该对象,这可能会导致问题。这两件事是不是自相矛盾。如果只有创建线程可以访问构造函数,那么其他线程如何过早地访问该对象,因为它只能在构造函数完全运行后才能访问? 任何输入都会有很大帮助。

最佳答案

假设两个线程都可以访问一个全局列表(称为“实例”),其中包含相关类的实例。线程 1 不断循环遍历列表并对每个实例执行某些操作。线程 2 走自己的路,偶尔会构造一个新的类实例。如果该类在其构造函数中将自己添加到列表中(使用 instances.add(this)),线程 1 将立即访问该实例并可以在它完全构造之前对其进行操作,从而导致不可预测的行为。

“应该”这个词可能会有误解。您写道:“首先,它声明只有创建对象的线程才能访问构造函数。”但是,Java 文档说:“只有创建对象的线程才能在构造对象时访问它”,这意味着您应该注意在构造对象时只有一个线程可以访问该对象。

关于multithreading - 构造函数中的过早泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31763653/

相关文章:

java - Python "Event"等同于 Java?

c# - 异步方法和异步委托(delegate)

c# - 多线程安全日志记录

c++ - 关于 C++ 中自定义对象的构造函数/析构函数和新建/删除运算符

c# - 使用析构函数分离事件

Java - 将等待/通知转换为 java.util.concurrent

c# - 使用 Kinect 线程

c++ - 错误 c2259 'class' : cannot instantiate abstract class

android - 与 SyncAdapter 的同步如何在 android 上工作?

java - 使用同步(锁定对象) block 时,静态锁定对象是否需要是最终的?