“Never lock when invoking methods on other objects…”
•Example adapted from CPiJ2e:
• class Particle {
protected int x; //
this object’s
protected int y; //
coordinates
…
public void Draw( Graphics g ) {
int localx, localy;
lock (this) { localx
= x; localy = y; } //
safely take copies
g.DrawRect( localx, localy, 10, 10 ); // call is outside any locks
}
};
•Active objects already have no need for
locking (they are inherently serialized), but still want to avoid blocking:
• public void Draw(
Graphics g ) {
return active{ g.DrawRect( x, y, 10, 10 ); }; //
safely takes copies
}
•Both avoid deadlock, but latter is
simpler… and more concurrent.