gpt4 book ai didi

构造后可见的 Java 非最终整数

转载 作者:搜寻专家 更新时间:2023-10-31 08:29:34 29 4
gpt4 key购买 nike

我有一个带有非最终 int 变量的 java 类,我在构造函数中将其显式初始化为 0。对该变量的所有其他访问都由 ReentrantLock 管理。我是否需要担心线程不会看到初始值 0,因为我没有在构造函数中使用锁?

最佳答案

是的,你必须担心。为避免在这种情况下出现问题,您需要安全发布对象引用。

来自 Java Concurrency in Practice :

To publish an object safely, both the reference to the object and the object's state must be made visible to other threads at the same time. A properly constructed object can be safely published by:

  • Initializing an object reference from a static initializer;
  • Storing a reference to it into a volatile field or AtomicReference;
  • Storing a reference to it into a final field of a properly constructed object; or
  • Storing a reference to it into a field that is properly guarded by a lock.

在其他情况下,您可以(理论上)面对 new 的结果在构造函数调用完成之前对其他线程可用的情况(由于可能的操作重新排序)。

但是请注意,如果 0 是默认值而不是构造函数中写入的值,则它保证可见(JLS §17.4.4):

  • The write of the default value (zero, false or null) to each variable synchronizes- with the first action in every thread. Although it may seem a little strange to write a default value to a variable before the object containing the variable is allocated, conceptually every object is created at the start of the program with its default initialized values

关于构造后可见的 Java 非最终整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5299543/

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