Java Reference
In-Depth Information
@NotThreadSafe
public class ArrayList<E> extends ... {
// ...
}
Documenting Locking Policies
It is important to document all the locks that are being used to protect shared state. Ac-
cording to Brian Goetz and colleagues [Goetz 2006],
For each mutable state variable that may be accessed by more than one thread, all
accesses to that variable must be performed with the same lock held. In this case, we
say that the variable is guarded by that lock. (p. 28)
JCIPprovidesthe @GuardedBy annotationforthispurpose,andSureLogicprovidesthe
@RegionLock annotation. The field or method to which the @GuardedBy annotation is ap-
plied can be accessed only when holding a particular lock. It may be an intrinsic lock or a
dynamic lock such as java.util.concurrent.Lock .
For example, the following MovablePoint class implements a movable point that can
remember its past locations using the memo array list:
Click here to view code image
@ThreadSafe
public final class MovablePoint {
@GuardedBy("this")
double xPos = 1.0;
@GuardedBy("this")
double yPos = 1.0;
@GuardedBy("itself")
static final List<MovablePoint> memo
= new ArrayList<MovablePoint>();
public void move(double slope, double distance) {
synchronized (this) {
rememberPoint(this);
xPos += (1 / slope) * distance;
yPos += slope * distance;
}
}
public static void rememberPoint(MovablePoint value) {
synchronized (memo) {
Search WWH ::




Custom Search