Java Reference
In-Depth Information
Documenting Intended Thread-Safety
JCIP provides three class-level annotations to describe the programmer's design intent
with respect to thread-safety.
The @ThreadSafe annotationisappliedtoaclasstoindicatethatitis 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.
For example, the following Aircraft class specifies that it is thread-safe as part of its
lockingpolicydocumentation.Thisclassprotectsthe x and y fieldsusingareentrantlock.
Click here to view code image
@ThreadSafe
@Region("private AircraftState")
@RegionLock("StateLock is stateLock protects AircraftState")
public final class Aircraft {
private final Lock stateLock = new ReentrantLock();
// ...
@InRegion("AircraftState")
private long x, y;
// ...
public void setPosition(long x, long y) {
stateLock.lock();
try {
this.x = x;
this.y = y;
} finally {
stateLock.unlock();
}
}
// ...
}
The @Region and @RegionLock annotations document the locking policy upon which
the promise of thread-safety is predicated.
Even when one or more @RegionLock or @GuardedBy annotations have been used to
document the locking policy of a class, the @ThreadSafe annotation provides an intuitive
way for reviewers to learn that the class is thread-safe.
Search WWH ::




Custom Search