Advertisement
Guest User

Almost final (first attempt)

a guest
Dec 23rd, 2011
189
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.98 KB | None | 0 0
  1. import java.lang.invoke.*;
  2.  
  3. public class AlmostFinal<T> {
  4.     private final MethodHandle getter;
  5.     private SwitchPoint switchPoint;
  6.     private VolatileCallSite callSite;
  7.    
  8.     public AlmostFinal(T initial) {
  9.         switchPoint = new SwitchPoint();
  10.         callSite = new VolatileCallSite(MethodType.genericMethodType(0));
  11.         getter = switchPoint.guardWithTest(MethodHandles.constant(Object.class, initial), callSite.dynamicInvoker());
  12.     }
  13.    
  14.     public T value() {
  15.         try {
  16.             return (T) getter.invokeExact();
  17.         } catch (Throwable t) {
  18.             throw new Error(t); // Shouldn't happen
  19.         }
  20.     }
  21.    
  22.     public synchronized void setValue(T val) {
  23.         final SwitchPoint[] invalid = { switchPoint };
  24.         switchPoint = new SwitchPoint();
  25.         final VolatileCallSite previousSite = callSite;
  26.         callSite = new VolatileCallSite(MethodType.genericMethodType(0));
  27.         previousSite.setTarget(switchPoint.guardWithTest(MethodHandles.constant(Object.class, val), callSite.dynamicInvoker()));
  28.         SwitchPoint.invalidateAll(invalid);
  29.     }
  30. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement