gpt4 book ai didi

具有昂贵操作的 Collection 上的 Java 同步

转载 作者:行者123 更新时间:2023-12-02 16:20:29 26 4
gpt4 key购买 nike

我有一个在我的函数 doMapOperation 中的名为 synchronizedMap 上同步的列表。在此函数中,我需要从 map 中添加/删除项目并对这些对象执行昂贵的操作。我知道我不想在同步块(synchronized block)中调用昂贵的操作,但我不知道在执行这些操作时如何确保映射处于一致状态。正确的做法是什么?

这是我的初始布局,我确信它是错误的,因为您想避免在同步块(synchronized block)中调用昂贵的操作:

public void doMapOperation(Object key1, Object key2) {
synchronized (synchronizedMap) {

// Remove key1 if it exists.
if (synchronizedMap.containsKey(key1)) {
Object value = synchronizedMap.get(key1);
value.doExpensiveOperation(); // Shouldn't be in synchronized block.

synchronizedMap.remove(key1);
}

// Add key2 if necessary.
Object value = synchronizedMap.get(key2);
if (value == null) {
Object value = new Object();
synchronizedMap.put(key2, value);
}

value.doOtherExpensiveOperation(); // Shouldn't be in synchronized block.
} // End of synchronization.
}

我想作为这个问题的延续,你会如何循环执行此操作?

public void doMapOperation(Object... keys) {
synchronized (synchronizedMap) {

// Loop through keys and remove them.
for (Object key : keys) {
// Check if map has key, remove if key exists, add if key doesn't.
if (synchronizedMap.containsKey(key)) {
Object value = synchronizedMap.get(key);
value.doExpensiveOperation(); // Shouldn't be here.

synchronizedMap.remove(key);
} else {
Object value = new Object();
value.doAnotherExpensiveOperation(); // Shouldn't here.

synchronizedMap.put(key, value);
}
}
} // End of synchronization block.
}

感谢您的帮助。

最佳答案

您可以在同步块(synchronized block)之外执行昂贵的操作,如下所示:

public void doMapOperation(Object... keys) {
ArrayList<Object> contained = new ArrayList<Object>();
ArrayList<Object> missing = new ArrayList<Object>();

synchronized (synchronizedMap) {
if (synchronizedMap.containsKey(key)) {
contained.add(synchronizedMap.get(key));
synchronizedMap.remove(key);
} else {
missing.add(synchronizedMap.get(key));
synchronizedMap.put(key, value);
}
}

for (Object o : contained)
o.doExpensiveOperation();
for (Object o : missing)
o.doAnotherExpensiveOperation();
}

唯一的缺点是您可能会对从 synchronizedMap 中删除的值执行操作。

关于具有昂贵操作的 Collection 上的 Java 同步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7906381/

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