Java Reference
In-Depth Information
}
}
public void reset() {
synchronized (lockA) {
synchronized (lockB) {
aVal = bVal = 0.0;
}
}
}
}
The two lock references are protected so that an extended class can
correctly synchronize its own methodssuch as a method to set
aVal
and
bVal
to the same value. Also notice how
reset
acquires both locks before
modifying both values.
Another common use of the
synchronized
statement is for an inner object
to synchronize on its enclosing object:
public class Outer {
private int data;
// ...
private class Inner {
void setOuterData() {
synchronized (Outer.this) {
data = 12;
}
}
}
}
Like any other object, an inner object is independently synchronizedac-
quiring the lock of an inner object has no effect on its enclosing object's
lock, nor does acquiring the lock of an enclosing object affect any en-