gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 04:15:37 30 4
gpt4 key购买 nike

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/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com