Java1.8 introduces a new lock, StampedLock, which can be considered an improvement on ReadWriteLock.

We know that in ReadWriteLock, writes and reads are mutually exclusive, meaning that if one thread writes a shared variable, other threads block reading the shared variable.

StampedLock divides reads into pessimistic reads and optimistic reads. Pessimistic reads are equivalent to ReadWriteLock reads, while optimistic reads are not blocked when a thread writes to a shared variable, and optimistic reads are not locked. So no lock is definitely better than lock performance, so in the case of large concurrent read efficiency is higher!

StampedLock is used slightly differently in that it returns a stamp on both lock acquisition and optimistic read, which is passed in to unlock, and in optimistic read to verify that the shared variable has been written by another thread. Take a look at the official example

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(); // get write lock try {x += deltaX; y += deltaY; } finally { sl.unlockWrite(stamp); // release write lock}} doubledistanceFromOrigin() { // A read-only method long stamp = sl.tryOptimisticRead(); // Double currentX = x, currentY = y;if(! Sl.validate (stamp)) {stamp = sl.readlock (); CurrentX = x; currentX = x; currentX = x; currentY = y; } finally { sl.unlockRead(stamp); // Release the pessimistic read lock}}return Math.sqrt(currentX * currentX + currentY * currentY);
   }

   void moveIfAtOrigin(double newX, double newY) { // upgrade
     // Could instead start with optimistic, not readmode long stamp = sl.readLock(); // Get read lock try {while(x == 0.0&&y == 0.0) {long ws = sl.tryconvertTowritelock (stamp); // Upgrade to write lockif(ws ! = 0L) { stamp = ws; x = newX; y = newY;break;
         }
         else{ sl.unlockRead(stamp); stamp = sl.writeLock(); } } } finally { sl.unlock(stamp); }}}Copy the code

If a write operation modifies the shared variable, the optimistic read is upgraded to the pessimistic read lock. In this way, the optimistic read repeatedly waits for the release of the write lock and avoids wasting CPU resources. Therefore, we recommend this operation when using StampedLock.

If StampedLock performs better than ReadWriteLock, should StampedLock discard ReadWriteLock?

No, StampedLock is not a reentrant lock, so it does not support reentrant, and StampedLock does not support conditional variables, that is, Condition. This can cause CPU spikes…. if an interrupt() occurs before a thread is finished executing after it has acquired a lock using writeLock() or readLock() Pit ah we look at the source code

public long readLock() {
    long s = state, next;  // bypass acquireRead on common uncontended case
    return ((whead == wtail && (s & ABITS) < RFULL &&
            U.compareAndSwapLong(this, STATE, s, next = s + RUNIT)) ?
            next : acquireRead(false, 0L)); // When the CAS fails, the lock will be attemptedfalse
}

public long writeLock() {
    long s, next;  // bypass acquireWrite in fully unlocked case only
    return ((((s = state) & ABITS) == 0L &&
            U.compareAndSwapLong(this, STATE, s, next = s + WBIT)) ?
            next : acquireWrite(false, 0L)); // When the CAS fails, the lock will be attemptedfalse} // Take acquireWrite, acquireRead is similar. private long acquireWrite(boolean interruptible, long deadline) { WNode node = null, p;for (int spins = -1;;) { // spin whileEnqueuing // Countless omitted codesif (interruptible && Thread.interrupted())
                return cancelWaiter(node, node, true); }}Copy the code

If (interruptible && Thread.interrupted()) returns false, thread.interrupted () will not be interrupted. If (interruptible && Thread.interrupted()) returns false. There will never be a cancelWaiter call, so the CPU usage will keep going up and up.

To use the interrupt function, use either readLockInterruptibly() or writeLockInterruptibly() to obtain the lock.


If there are mistakes welcome to correct! Personal public account: Yes training level guide