I have a CircleImpl class which implements a circle that can exist only on the positive side of the XY (radius>=0, x>=radius and y>=radius.)
I have a function in 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()));
}
}
Now the problem that here a deadlock can exist:
Circle c1,c2;
…
T1: c1.union(c2);
T2: c2.union(c1);
c1 locks itself (this) and before it locks “other” (c2) c2 gets CPU time and locks itself (c2) and tries to lock “other” (c1) and enters blocking mode.
What possible SIMPLE solution to this that does not include resource-ordering (System.identityHashCode)?
Simple (but not really efficient) solution would be to synchronize
unionoperation on shared object, e.g. onCircle.class. Downside that it will allow to executeuniononly for 1 thread at any given time. Something like: