VarHandle compareAndExchange Witness Value
compareAndExchange returns the witness value: the expected value on success, but on failure the actual current value, which boolean CAS cannot reveal.
Code
import java.lang.invoke.MethodHandles;
import java.lang.invoke.VarHandle;
public class WitnessCas {
private int version = 10;
public static void main(String[] args) throws ReflectiveOperationException {
WitnessCas app = new WitnessCas();
VarHandle handle = MethodHandles.lookup()
.findVarHandle(WitnessCas.class, "version", int.class);
// 成功路径:witness == expected,返回期望值本身
int witness = (int) handle.compareAndExchange(app, 10, 20);
System.out.println("success witness: " + witness);
// 失败路径:witness 是当前实际值——布尔 CAS 只能给 false,
// 而 compareAndExchange 直接告诉你现场是什么
witness = (int) handle.compareAndExchange(app, 10, 30);
System.out.println("failure witness: " + witness);
// 同一信息可写"读-改-写"循环:失败时立刻用 witness 重试
witness = (int) handle.compareAndExchange(app, 10, 30);
if (witness != 10) {
witness = (int) handle.compareAndExchange(app, witness, witness + 1);
System.out.println("retry with witness, now: " + (int) handle.get(app));
}
}
}What the code does
VarHandle compareAndExchange Witness Value keeps everything in the class WitnessCas.
Caveats
- No lockfile entry, no version pinning — the file needs nothing beyond the runtime.
Applying it
Look for the success witness:, failure witness:, retry with witness, now: prefixes during the file’s run; they match each line of output to the step that emitted it.
Statements that matter most here
witness = (int) handle.compareAndExchange(app, witness, witness + 1);
int witness = (int) handle.compareAndExchange(app, 10, 20);
.findVarHandle(WitnessCas.class, "version", int.class);
Interactive Tools for This Topic
FAQ
- What does VarHandle compareAndExchange Witness Value print when run?
- No setup needed: run the file and look for labeled lines like `success witness:`, `failure witness:`, `retry with witness, now:` in the output.
Report a problem with this exampleOpens a pre-filled issue on GitHub.