@GenerateMicroBenchmark @Group("Stamped") @GroupThreads(1) public long stWrites() { long stamp; long newValue; stamp = stampedLock.readLock(); try { BlackHole.consumeCPU(consumedCPU); long currentValue = stampedAdder; newValue = currentValue + 1; long writeStamp = stampedLock.tryConvertToWriteLock(stamp); if (writeStamp != 0L) { stamp = writeStamp; stampedAdder = newValue; } else { stampedLock.unlockRead(stamp); stamp = stampedLock.writeLock(); BlackHole.consumeCPU(consumedCPU); currentValue = stampedAdder; newValue = currentValue + 1; stampedAdder = newValue; } } finally { stampedLock.unlock(stamp); } BlackHole.consumeCPU(consumedCPU); return newValue; }
@Override public void increment() { long stamp = stampedLock.writeLock(); // blocking lock, returns a stamp try { counter++; } finally { stampedLock.unlockWrite(stamp); // release the lock in the same block } }
@Override public long getResult() { long stamp = stampedLock.tryOptimisticRead(); // non blocking long result = counter; if (!stampedLock.validate(stamp)) { // if a write occurred, try again with a read lock stamp = stampedLock.readLock(); try { return counter; } finally { stampedLock.unlockRead(stamp); } } return result; }
@GenerateMicroBenchmark @Group("Stamped") @GroupThreads(1) public long stReads() { long stamp; long currentValue; stamp = stampedLock.tryOptimisticRead(); BlackHole.consumeCPU(consumedCPU); currentValue = stampedAdder; if (!stampedLock.validate(stamp)) { stamp = stampedLock.readLock(); try { BlackHole.consumeCPU(consumedCPU); currentValue = stampedAdder; } finally { stampedLock.unlockRead(stamp); } } return currentValue; }