gpt4 book ai didi

java - Java 中的双重检查锁定问题

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:22:08 25 4
gpt4 key购买 nike

<分区>

其中一篇文章提到了 “Double Check Locking” 的问题。请看下面的例子

public class MyBrokenFactory {
private static MyBrokenFactory instance;
private int field1, field2 ...

public static MyBrokenFactory getFactory() {
// This is incorrect: don't do it!
if (instance == null) {
synchronized (MyBrokenFactory.class) {
if (instance == null)
instance = new MyBrokenFactory();
}
}
return instance;
}

private MyBrokenFactory() {
field1 = ...
field2 = ...
}
}

原因:-(请注意编号的执行顺序)

Thread 1: 'gets in first' and starts creating instance.1. Is instance null? Yes.2. Synchronize on class.3. Memory is allocated for instance.4. Pointer to memory saved into instance.[[Thread 2]]7. Values for field1 and field2 are writtento memory allocated for object......................Thread 2: gets in just as Thread 1 has written the object referenceto memory, but before it has written all the fields.5. Is instance null? No.6. instance is non-null, but field1 and field2 haven't yet been set!   This thread sees invalid values for field1 and field2!

问题:
由于新实例(new MyBrokenFactory())的创建是从synchronized block 中完成的,在整个初始化完成之前(private MyBrokenFactory()完全执行)是否会释放锁?

引用 - https://www.javamex.com/tutorials/double_checked_locking.shtml

请解释。

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