gpt4 book ai didi

java - Java新内存模型中的happens-before是否也适用于声明为 volatile 的对象的成员?

转载 作者:行者123 更新时间:2023-12-02 06:57:42 27 4
gpt4 key购买 nike

在新的 Java 内存模型中,对变量的任何写入都保证在下一个线程读取它之前完成。

我想知道作为该对象成员的变量是否也是这种情况。

对于java内存模型:

http://www.cs.umd.edu/~pugh/java/memoryModel/jsr-133-faq.html

例如

public class VolatileTest {
private volatile Map<String, Function> functionMap = new HashMap<>();

public Function getFunction(String key) {
Function function = this.functionMap.get(key);

if (function == null) {
//Is this guaranteed to be fully constructed? I don't think so.
function = new Function(key);

this.functionMap.put(key, function);
}

return function;
}
}

与上面的代码一样,即使使 functionMap 为 volatile ,它仍然不能保证函数对象在此方法返回之前完全构造完毕。

我的想法对吗?

也只是针对这个主题,我希望你们检查一下我的想法是否正确:

如下所示,对 functionMap 的任何写入都保证在更改 functionMap 的引用之前完成,对吧?无论 initializeMap 方法花费多长时间,另一个线程要么会看到空的 functionMap,要么会看到完全初始化的 functionMap

public Map<String,Function> getFunctionMap (){
Map<String, Function> tempMap = new HashMap<>();

initalizeMap(tempMap); //fill in values

// Above operation is guaranteed to be completed
// before changing the reference of this variable.
this.functionMap = tempMap;

// So here you will either see a null or a fully initialized map.
// Is my understanding right?
return this.functionMap;
}

澄清一下,上面的两个例子都是在多线程环境下,functionMap 变量将被多个线程访问。

最佳答案

这正是应该使用 ConcurrentHashMap 的时候

private final ConcurrentMap<String, Function> functionMap = new ConcurrentHashMap<>();

public Function getFunction(String key) {
Function function = functionMap.get(key);
if (function == null) {
function = new Function(key);
Function oldFunction = functionMap.putIfAbscent(function);
if (oldFunction != null) {
function = oldFunction;
}
}
return function;
}

关于java - Java新内存模型中的happens-before是否也适用于声明为 volatile 的对象的成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17104380/

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