有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java防止圆联合上的死锁

我有一个CircleImpl类,它实现了一个只能存在于XY正边的圆(半径>;=0,x>;=radius,y>;=radius)

我在CircleImpl中有一个函数:

//this function changes the current circle (this) to make it contain the circle other.
public synchronized void union(Circle other) throws Exception { 
 if (!checkInv(other.getX(),other.getY(),other.getRadius())) 
     throw new Exception("Illegal circle: " + other); 
  synchronized (other) { 
     setRadius(calculateUnionRadius(_x,_y,_radius,other.getX(),other.getY(),other.getRadius())); 
  } 
} 

现在的问题是,这里可能存在死锁:

Circle c1,c2; 
… 
T1: c1.union(c2); 
T2: c2.union(c1); 

c1锁定自身(此),在锁定“其他”(c2)之前,c2获得CPU时间并锁定自身(c2),尝试锁定“其他”(c1)并进入阻塞模式

有什么可能的简单解决方案不包括资源排序(System.identityHashCode)


共 (1) 个答案

  1. # 1 楼答案

    简单(但不是真正有效)的解决方案是同步共享对象上的union操作,例如Circle.class。缺点是,它将允许在任何给定时间仅为1个线程执行union。比如:

    public void union(Circle other) throws Exception { 
        synchronized (Circle.class) {
           if (!checkInv(other.getX(),other.getY(),other.getRadius())) {
               throw new Exception("Illegal circle: " + other); 
           }
           setRadius(calculateUnionRadius(_x,_y,_radius,other.getX(),other.getY(),other.getRadius())); 
        } 
    }