Java Reference
In-Depth Information
private long altitude;
// ...
public void setPosition(long x, long y) {
stateLock.lock();
try {
this.x = x;
this.y = y;
} finally {
stateLock.unlock();
}
}
// ...
}
In this example, a locking policy named
StateLock
is used to indicate that locking
on
stateLock
protectsthenamed
AircraftPosition
region,whichincludesthemutable
state used to represent the position of the aircraft.
Construction of Mutable Objects
Typically,objectconstructionisconsideredanexceptiontothelockingpolicybecauseob-
jects are thread-confined when they are first created. An object is confined to the thread
that uses the
new
operator to create its instance. After creation, the object can be pub-
lished to other threads safely. However, the object is not shared until the thread that cre-
ated the instance allows it to be shared. Safe publication approaches discussed in
The
CERT
®
Oracle
®
Secure Coding Standard for Java
™
[Long 2012], “TSM01-J. Do not let
the
this
reference escape during object construction,” can be expressed succinctly with
the
@Unique("return")
annotation.
For example, in the following code, the
@Unique("return")
annotation documents
that the object returned from the constructor is a unique reference:
@RegionLock("Lock is this protects Instance")
public final class Example {
private int x = 1;
private int y;
@Unique("return")
public Example(int y) {
this.y = y;
}