StampedLock
This is equivalent to a performance improvement for read/write locks; StampedLock supports three modes: write lock, pessimistic read lock, and Optimistic read lock. Write locks and pessimistic read locks have the same semantics as ReadWriterLock. The difference is that the write lock and pessimistic read lock in StampedLock return a stamp after the lock is successfully added. Then when unlocking, you need to pass in the stamp; Does not support reentry and does not support the condition variable.
Official usage examples:
class Point {
private double x, y;
private final StampedLock sl = new StampedLock();
void move(double deltaX, double deltaY) { // an exclusively locked method
long stamp = sl.writeLock();
try {
x += deltaX;
y += deltaY;
} finally{ sl.unlockWrite(stamp); }}double distanceFromOrigin(a) { // A read-only method
long stamp = sl.tryOptimisticRead();
double currentX = x, currentY = y;
if(! sl.validate(stamp)) { stamp = sl.readLock();try {
currentX = x;
currentY = y;
} finally{ sl.unlockRead(stamp); }}return Math.sqrt(currentX * currentX + currentY * currentY);
}
void moveIfAtOrigin(double newX, double newY) { // upgrade
// Could instead start with optimistic, not read mode
long stamp = sl.readLock();
try {
while (x == 0.0 && y == 0.0) {
long ws = sl.tryConvertToWriteLock(stamp);//a valid write stamp, or zero on failure
if(ws ! =0L) {
stamp = ws;
x = newX;
y = newY;
break;
}
else{ sl.unlockRead(stamp); stamp = sl.writeLock(); }}}finally{ sl.unlock(stamp); }}}Copy the code
Unlock the sl. Unlock (stamp);
Unlocking requires passing in the stamp that is returned when the lock is acquired
Verify whether optimistic read lock is invalid sl.validate(stamp)
/**
* Returns true if the lock has not been exclusively acquired
* since issuance of the given stamp. Always returns false if the
* stamp is zero. Always returns true if the stamp represents a
* currently held lock. Invoking this method with a value not
* obtained from {@link #tryOptimisticRead} or a locking method
* for this lock has no defined effect or result.
*
* @param stamp a stamp
* @return {@code true} if the lock has not been exclusively acquired
* since issuance of the given stamp; else false
*/
Copy the code
Returns true if self-stamp has not acquired the lock exclusively since its release. If stamp is zero, always return false. Always return true if stamp represents the currently held lock. Call an effect or result that is not defined by this method with a value not obtained from tryOptimisticRead or the locking method of this lock.
Lock escalation sl. TryConvertToWriteLock (stamp);
The read lock is upgraded to a write lock, and the write lock is released by passing sl.tryconvertToWritelock (stamp). Return new stamp;
Do not call interrupt operations when using StampedLock. If you want to support interrupt functions, always use the interruptible pessimistic read lock readLockInterruptibly() and write lock writeLockInterruptibly().