在java中以原子方式获取多个锁 [英] Acquiring multiple locks atomically in java

查看:102
本文介绍了在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
    }
}

此实施应确保所有关系x,y with:

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

x.user = u_x
y.user = u_y

以下不变量持有:

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

我认为上述代码是否成立?

I believe that holds for the code stated above?

注意:它当然不会在执行setRelation(..),
时保持不变,但是在那一刻,所涉及的两个关系的锁都是
持有的执行线程所以没有其他线程可以读取所涉及的一个关系的
hasRelation(..)。

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.

假设这个持有我认为仍然存在潜在的死锁风险。
这是对的吗?如果是,我该如何解决?
我想我需要以某种方式原子地获取setRelation(..)中的两个锁。

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.

推荐答案

你是对的在这两点上:你的不变量确实成立(假设我正确理解你的方法名称是什么意思等等,并假设通过 if(!relations.hasRelation(user))relations2.setRelation(user2) ; 你打算写 if(!relations2.hasRelation(user))relations2.setRelation(user); ),但你确实有风险死锁:如果一个线程需要在 x 上获得锁定,然后在 y 上获取锁定,另一个线程需要获取 y 的锁定,然后在 x 上获取锁定,那么每个线程都有成功获取其首先锁定,从而防止对方获得第二次锁定。

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.

一种解决方案是强制执行严格的通用排序获取 Relations 实例的锁定。你要做的是,你添加一个常量整数字段 lockOrder

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;

和一个静态整数字段 currentLockOrder

private static int currentLockOrder = 0;

以及每次创建 Relations 实例时,将 lockOrder 设置为 currentLockOrder 的当前值,并增加说:

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;
    }
}

这样每个的实例关系将具有 lockOrder 的不同的不可变值。您的 setRelation 方法将按指定的顺序获取锁定:

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);
        }
    }
}

从而确保如果两个线程两者都需要锁定 x y ,然后他们都要先锁定 x ,或者他们都会先在 y 上获得锁定。无论哪种方式,都不会发生死锁。

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.

请注意,我将 setRelation 更改为 storeRelation setRelation 会起作用,但为什么会增加这种复杂性呢?

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

此外,还有一件事我没有得到:怎么来 x.setRelation(u_y)调用 x.storeRelation(u_y) 无条件地,但只有 y.setRelation(u_x)(或 y.storeRelation(u_x)) > y 还没有关系吗?这没有意义。似乎需要两个检查,或者都不检查。 (没有看到 Relations.storeRelation(...)的实现,我无法猜测是哪种情况。)

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.)

这篇关于在java中以原子方式获取多个锁的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆