Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

The @ThreadSafe annotation is applied to a class to indicate that it is thread-safe. This means that no sequences of accesses (reads and writes to public fields, calls to public methods) can leave the object in an inconsistent state, regardless of the interleaving of these accesses by the runtime or any external synchronization or coordination on the part of the caller.

...

Code Block
bgColor#ccccff
@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) {
      memo.add(value);
    }
  }
}

The @GuardedBy annotations on the xPos and yPos fields indicate that access to these fields is protected by holding a lock on this (also done in the . The move() method also synchronizes on this, which modifies these fields). The @GuardedBy annotation on the memo list indicates that a lock on the ArrayList object protects its contents (also done in the . The rememberPoint() method )also synchronizes on the memo list.

One issue with the @GuardedBy annotation is that it fails to indicate that when there is a relationship between the fields of a class. This limitation can be overcome by using the SureLogic @RegionLock annotation, which declares a new region lock for the class to which this annotation is applied. This declaration creates a new named lock that associates a particular lock object with a region of the class. The region may be accessed only when the lock is held. For example, the SimpleLock locking policy indicates that synchronizing on the instance protects all of its state:

...