|
| 1 | +package org.armedbear.lisp; |
| 2 | + |
| 3 | +import static org.armedbear.lisp.Lisp.*; |
| 4 | + |
| 5 | +import java.lang.invoke.MethodHandles; |
| 6 | +import java.lang.invoke.VarHandle; |
| 7 | + |
| 8 | +public class Atomic |
| 9 | +{ |
| 10 | + static MethodHandles.Lookup Lookup |
| 11 | + = MethodHandles.lookup(); |
| 12 | + |
| 13 | + static boolean compareAndSwap(LispObject place, LispObject expectedValue, LispObject newValue) { |
| 14 | + VarHandle vh = null; |
| 15 | + if (place instanceof Fixnum) { |
| 16 | + try { |
| 17 | + vh = Lookup.findVarHandle(Fixnum.class, "value", int.class); |
| 18 | + } catch (ReflectiveOperationException e) { |
| 19 | + java_error(e); |
| 20 | + return false; // unreached |
| 21 | + } |
| 22 | + } |
| 23 | + if (vh == null) { |
| 24 | + simple_error("Unable to find VarHandle for place ~a", place); |
| 25 | + return false; // unreached |
| 26 | + } |
| 27 | + return vh.compareAndSet(expectedValue, newValue); |
| 28 | + } |
| 29 | + |
| 30 | + public static final Primitive _CAS = new pf_cas(); |
| 31 | + @DocString(name="%cas", |
| 32 | + args="place expected-value new-value", |
| 33 | + returns="generalized boolean") |
| 34 | + private static final class pf_cas extends Primitive { // Maybe a special operator? Or do that Lisp-side? |
| 35 | + pf_cas() { |
| 36 | + super(Symbol._CAS); |
| 37 | + } |
| 38 | + @Override |
| 39 | + public LispObject execute(LispObject place, LispObject expectedValue, LispObject newValue) { |
| 40 | + boolean result = compareAndSwap (place, expectedValue, newValue); |
| 41 | + return (result == false) ? NIL : T; // TODO this has to exist somewhere as a static method |
| 42 | + } |
| 43 | + } |
| 44 | +} |
0 commit comments