gpt4 book ai didi

java - 在对象上同步并更改引用

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:07:00 26 4
gpt4 key购买 nike

假设我有一个对象如下:

Map<String, String> m = new HashMap<>();

然后我按如下方式同步此对象并更改其引用:

synchronize(m){
m = new HashMap<>();
}

使用这段代码,m 上的锁会怎样?更新由 m 表示的新对象是否仍然安全?或者锁本质上是在旧对象上?

最佳答案

来自 JLS 17.1 :

The synchronized statement (§14.19) computes a reference to an object; it then attempts to perform a lock action on that object's monitor and does not proceed further until the lock action has successfully completed. After the lock action has been performed, the body of the synchronized statement is executed. If execution of the body is ever completed, either normally or abruptly, an unlock action is automatically performed on that same monitor.

现在是问题。

m 上的锁发生了什么?

没有。这有点令人困惑。实际上,该线程在尝试获取锁时正在持有 m 引用的对象上的锁。在同步块(synchronized block)中对 m 的赋值不会自动“切换”正在执行的线程持有的锁。

更新由 m 表示的新对象是否仍然安全?

这不安全。对 m 的写入未在同一锁上同步。

或者锁本质上是在旧对象上?

关于java - 在对象上同步并更改引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40645658/

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