码迷,mamicode.com
首页 > 其他好文 > 详细

通过 UNSAFE 来实现一个 Atomic 的 CAS 辅助类【原创】

时间:2019-12-16 13:21:24      阅读:135      评论:0      收藏:0      [点我收藏+]

标签:ati   volatile   nsa   declare   原创   ons   wap   vat   als   

 

public abstract class AbstractUnSafeCas<T> {

  @SuppressWarnings("unused")
  private volatile Object value;

  private static final AtomicHelper ATOMIC_HELPER;

  private final CountDownLatch countDownLatch = new CountDownLatch(1);

  static {
    ATOMIC_HELPER = new AtomicHelper();
  }

  private static class AtomicHelper {

    private static final sun.misc.Unsafe UNSAFE;

    private static final long VALUE_OFFSET;

    static {
      sun.misc.Unsafe unsafe;
      try {
        unsafe = sun.misc.Unsafe.getUnsafe();
      } catch (SecurityException tryReflectionInstead) {
        unsafe = AccessController.doPrivileged(new PrivilegedAction<Unsafe>() {
          @Override
          @SneakyThrows
          public Unsafe run() {
            Class<sun.misc.Unsafe> unsafeClass = sun.misc.Unsafe.class;
            for (Field f : unsafeClass.getDeclaredFields()) {
              f.setAccessible(true);
              Object o = f.get(null);
              if (unsafeClass.isInstance(o)) {
                return unsafeClass.cast(o);
              }
            }
            throw new NoSuchFieldError("the Unsafe");
          }
        });
      }
      try {
        VALUE_OFFSET = unsafe.objectFieldOffset(AbstractUnSafeAtomicHelper.class.getDeclaredField("value"));
      } catch (Exception e) {
        throw Throwables.propagate(e);
      }
      UNSAFE = unsafe;
    }

    public boolean casValue(AbstractUnSafeAtomicHelper<?> obj, Object expect, Object update) {
      return UNSAFE.compareAndSwapObject(obj, VALUE_OFFSET, expect, update);
    }

  }

  public boolean set(T value) {
    Preconditions.checkArgument(null != value, "The value to be setted is null");
    if (ATOMIC_HELPER.casValue(this, null, value)) {
      countDownLatch.countDown();
      return true;
    }
    return false;
  }

  @SneakyThrows
  public T get(boolean blockUntilValueIsNotNull) {
    if (blockUntilValueIsNotNull) {
      countDownLatch.await();
    }
    @SuppressWarnings("unchecked")
    T asT = (T) value;
    return asT;
  }

  @SneakyThrows
  public T get(Long timeout, TimeUnit timeUnit) {
    countDownLatch.await(timeout, timeUnit);
    @SuppressWarnings("unchecked")
    T asT = (T) value;
    return asT;
  }

}

 

通过 UNSAFE 来实现一个 Atomic 的 CAS 辅助类【原创】

标签:ati   volatile   nsa   declare   原创   ons   wap   vat   als   

原文地址:https://www.cnblogs.com/frankyou/p/12048439.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!