Want more features on Pastebin? Sign Up, it's FREE!
Guest

Almost final (first attempt)

By: a guest on Dec 23rd, 2011  |  syntax: Java  |  size: 0.98 KB  |  views: 157  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  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. }
clone this paste RAW Paste Data