yas*_*eco 3 java multithreading caching thread-safety data-structures
我有一个ConcurrentHashMap用作内存存储(或者你可能会说的缓存)
我想要实现的是:同时检查某个项目是否“准备好”,如果是,则将其从地图中删除(+将其返回给调用者)。没有直接的方法可以让我做到这一点。
我想出的唯一解决方案是拥有一个ItemContainer包含项目和元数据(isReady字段)的项目。每次访问时,我都必须进行申请merge或compute操作。本质上是在每次访问/检查时替换对象的容器。
问题:
我根据要求添加了“样板”代码:
public class Main {
public static void main(String[] args) {
Storage storage = new Storage();
storage.put("1", new Record("s", 100));
storage.put("2", new Record("s", 4));
storage.removeIf("1", Main::isReady);
}
public static boolean isReady(Record record) {
return record.i > 42;
}
public static class Record {
public Record(String s, Integer i) {
this.s = s;
this.i = i;
}
String s;
Integer i;
}
public static class Storage {
ConcurrentHashMap<String, Record> storage = new ConcurrentHashMap<>();
public void put(String key, Record record) {
storage.put(key, record);
}
public Record removeIf(String key, Function<Record, Boolean> condition) {
return null; // TODO: implement
}
}
}
Run Code Online (Sandbox Code Playgroud)
其他解决方案(需要权衡):
remove()检查状态,然后merge()返回地图。基于@ernest_k解决方案:
public Record removeIf(String key, Predicate<Record> condition) {
AtomicReference<Record> existing = new AtomicReference<>();
this.storage.computeIfPresent(key, (k, v) -> {
boolean conditionSatisfied = condition.test(v);
if (conditionSatisfied) {
existing.set(v);
return null;
} else {
existing.set(null);
return v;
}
});
return existing.get();
}
Run Code Online (Sandbox Code Playgroud)
ConcurrentHashMap已经为您提供了原子性保证computeIfPresent。
如果指定键的值存在,则尝试计算给定键及其当前映射值的新映射。整个方法调用是原子执行的。当计算正在进行时,其他线程对此映射的某些尝试更新操作可能会被阻止,因此计算应该简短且简单,并且不得尝试更新此映射的任何其他映射。
所以你可以使用它:
public Record removeIf(String key, Predicate<Record> condition) {
AtomicReference<Record> existing = new AtomicReference<>();
this.storage.computeIfPresent(key, (k, v) -> {
existing.set(v);
return condition.test(v) ? null : v;
});
return existing.get();
}
Run Code Online (Sandbox Code Playgroud)
请注意,我使用的Predicate<Record>应该是Function<Record, Boolean>.
将当前值存储在此处的原因AtomicReference是为了确保返回的值与测试谓词的值相同(否则可能存在竞争条件)。
| 归档时间: |
|
| 查看次数: |
2829 次 |
| 最近记录: |