Walt
Walt

Reputation: 1436

Efficiently synchronizing a list in Java

I have a list and a particular operation can affect 4 nodes - current, previous, next and head. Is there any way I can lock this operation so that rest of the list entries are free to be accessed and changed ?

I tried finding out if one can obtain a lock of multiple list entries but not able to find anything.

PS: This is my first day in life playing with concurrency and multi threading.

Upvotes: 1

Views: 89

Answers (1)

Dima
Dima

Reputation: 40510

The most efficient way is, probably, to use indexes of the nodes (keep a bitset, indicating which nodes are currently locked), but that would break if you also want to concurrently add or remove nodes to the (middle of) the list. If that is not the requirement, then, perhaps, you should revisit the "lock by index" idea.

Meanwhile, consider something like this:

class NodeLocker {
    HashSet<Node> lockedNodes = new HashSet();
    protected boolean tryLock(List<Node> nodes) {                   
        for(n: Nodes) {
            if(lockedNodes.contains(n)) return false;
        }
        lockedNodes.addAll(nodes);
        return true;
    }
    public synchronized void lock(Node ... nodes) throws InterruptedException {
        while(!tryLock(Arrays.asList(nodes))) wait();
    }
    public synchronized void unlock(Node ... nodes) {
        lockedNodes.removeAll(Arrays.asList(nodes));
        notify();
    }
}

Upvotes: 1

Related Questions