Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Acquiring multiple locks atomically in java

I have the following code: Note: I simplified the code as much as possible for readability. If I forgot any critical pieces let me know.

public class User(){

    private Relations relations;

    public User(){
        relations = new Relations(this);
    }   

    public getRelations(){
        return relations;
    }
}


public class Relations(){

    private User user;

    public Relations(User user){
        this.user = user;
    }

    public synchronized void setRelation(User user2){
        Relations relations2 = user2.getRelations();

        synchronized(relations2){

            storeRelation(user2);

            if(!relations2.hasRelation(user))
                relations2.setRelation(user);
        }
    }   

    public synchronized boolean hasRelation(User user2){
        ... // Checks if this relation is present in some kind of collection
    }

    /*Store this relation, unless it is already present*/
    private void storeRelation(User user2){
        ... // Stores this relation in some kind of collection
    }
}

This implementation should make sure that for all Relations x, y with:

x.user = u_x
y.user = u_y

the following invariant holds:

x.hasRelation( u_y ) <=> y.hasRelation( u_x )

I believe that holds for the code stated above?

Note: It does of course not hold during the execution of setRelation(..), but at that moment the locks for both relations involved are held by the executing thread so no other thread can read the hasRelation(..) of one of the relations involved.

Assuming that this holds i believe there is still a potential deadlock-risk. Is that correct? And if it is, how can I solve it? I think i would need to obtain both locks in setRelation(..) atomically somehow.

like image 784
Antiz Avatar asked Mar 04 '12 13:03

Antiz


1 Answers

You are correct on both points: your invariant does hold (assuming that I understand correctly what your method-names mean and so on, and assuming that by if(!relations.hasRelation(user)) relations2.setRelation(user2); you meant to write if(!relations2.hasRelation(user)) relations2.setRelation(user);), but you do have the risk of a deadlock: if one thread needs to obtain a lock on x and then on y, and another thread needs to obtain a lock on y and then on x, then there's a risk that each thread will succeed in getting its first lock, and thereby prevent the other from getting its second lock.

One solution is to enforce a strict universal ordering for getting locks on Relations instances. What you do is, you add a constant integer field lockOrder:

private final int lockOrder;

and a static integer field currentLockOrder:

private static int currentLockOrder = 0;

and every time you create a Relations instance, you set its lockOrder to the current value of currentLockOrder, and increment said:

public Relations()
{
    synchronized(Relations.class) // a lock on currentLockOrder
    {
        lockOrder = currentLockOrder;
        ++currentLockOrder;
    }
}

such that every instance of Relations will have a distinct, immutable value for lockOrder. Your setRelation method would then obtain locks in the specified order:

public void setRelation(final User thatUser)
{
    final Relations that = thatUser.getRelations();

    synchronized(lockOrder < that.lockOrder ? this : that)
    {
        synchronized(lockOrder < that.lockOrder ? that : this)
        {
            storeRelation(thatUser);

            if(! that.hasRelation(user))
                that.storeRelation(user);
        }
    }
}

thereby ensuring that if two threads both need to get locks on both x and y, then either they'll both first get locks on x, or they'll both first get locks on y. Either way, no deadlock will occur.

Note, by the way, that I changed setRelation to storeRelation. setRelation would work, but why add that complexity?

Also, there's still one thing I don't get: how come x.setRelation(u_y) calls x.storeRelation(u_y) unconditionally, but calls y.setRelation(u_x) (or y.storeRelation(u_x)) only if y doesn't already have the relationship? It doesn't make sense. It seems like either both checks are needed, or neither check is. (Without seeing the implementation of Relations.storeRelation(...), I can't guess which of those is the case.)

like image 196
ruakh Avatar answered Sep 30 '22 18:09

ruakh