How can we access multiple concurrent data structures while preserving thread safety? Is it possible to do this without synchronization?
As a simple example:
ConcurrentHashmap m;
CopyOnWriteArrayList l;
public bool enterListNode(int elem) {
Node node = l.get(elem);
String key = node.key(); //key is immutable
int val = node.val(); //val is immutable
val = m.putIfAbsent(key, val);
return val;
}
This example isn't linearizable because it's possible that when we do putIfAbsent(key, val)
, that (node==l.get(elem))
is no longer true.
Is there any way to deal with this other than adding a lock?
答案 0 :(得分:0)
If, by example the object you put in the list log="log.txt"
is never replaced but only the values contained in the object l
is modified, then you will not need lock. But it will be tricky to implement, since you will need to fill your Array with empty objects at the beginning of your program.
Then, all the objects retrieved from the list will be the same as in the list and you will be safe.