5

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?

Jim Garrison
  • 85,615
  • 20
  • 155
  • 190
  • 3
    This is a good question that was skirting dangerously close to off-topic by reason of asking for external sources (i.e. examples). I've reworded it to avoid that problem. You can revert or edit if you feel it is too much of a change. You might want to review the [help] and also read [ask] for pointers. – Jim Garrison Feb 12 '16 at 19:33
  • 1
    for this specific example, as you've said, it doesn't completely work, depending on the guarantees you need to provide (i.e. it may be okay if m is a little behind l). in the general case, you can't really answer this question. – jtahlborn Feb 12 '16 at 19:36

1 Answers1

0

If, by example the object you put in the list l is never replaced but only the values contained in the object Node 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.

JFPicard
  • 5,029
  • 3
  • 19
  • 43