Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

StampedLock — optimistic reading

StampedLock provides exclusive writing, shared reading, and optimistic reading with validation.

Version: Java SE 21; repository runtime, production runtime not attested

Syntax

StampedLock lock = new StampedLock();
long stamp = lock.writeLock();
try { /* update protected state */ } finally { lock.unlockWrite(stamp); }
long optimistic = lock.tryOptimisticRead();
/* copy fields into locals before validation */
if (!lock.validate(optimistic)) {
    long read = lock.readLock();
    try { /* reread protected state */ } finally { lock.unlockRead(read); }
}

StampedLock.writeLock() waits for exclusive access; StampedLock.readLock() allows concurrent readers. Release using the returned long stamp with StampedLock.unlockWrite(stamp) or StampedLock.unlockRead(stamp) in finally.

StampedLock.tryOptimisticRead() does not block writers; it returns 0 during writing. Copy fields into locals, then call StampedLock.validate(stamp): true means no write-lock acquisition since issuance; 0 yields false. On failure, reread under readLock(). Optimistic reads need no unlocking.

Before validation, data may be inconsistent: avoid side effects and unsafe dereferencing. All writes must use the same lock. It is non-reentrant; reacquisition can deadlock.

Examples

import java.util.concurrent.locks.StampedLock;

public class Main {
    private final StampedLock lock = new StampedLock();
    private int left;
    private int right;

    void set(int a, int b) {
        long stamp = lock.writeLock();
        try {
            left = a;
            right = b;
        } finally {
            lock.unlockWrite(stamp);
        }
    }

    int sum() {
        long stamp = lock.tryOptimisticRead();
        int a = left;
        int b = right;
        if (!lock.validate(stamp)) {
            stamp = lock.readLock();
            try {
                a = left;
                b = right;
            } finally {
                lock.unlockRead(stamp);
            }
        }
        return a + b;
    }

    public static void main(String[] args) {
        Main pair = new Main();
        pair.set(10, 20);
        System.out.println(pair.sum());
    }
}

Result

30

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources