标签:wapi cpu asp pen 加载 版本 api var 交换
public final native boolean compareAndSwapObject(Object var1, long var2, Object var4, Object var5); public final native boolean compareAndSwapInt(Object var1, long var2, int var4, int var5); public final native boolean compareAndSwapLong(Object var1, long var2, long var4, long var6);
#define FN_PTR(f) CAST_FROM_FN_PTR(void*, &f) {CC"compareAndSwapObject", CC"("OBJ"J"OBJ""OBJ")Z", FN_PTR(Unsafe_CompareAndSwapObject)}, {CC"compareAndSwapInt", CC"("OBJ"J""I""I"")Z", FN_PTR(Unsafe_CompareAndSwapInt)}, {CC"compareAndSwapLong", CC"("OBJ"J""J""J"")Z", FN_PTR(Unsafe_CompareAndSwapLong)},
1 jbyte Atomic::cmpxchg(jbyte exchange_value, volatile jbyte*dest, jbyte compare_value) { 2 assert (sizeof(jbyte) == 1,"assumption."); 3 uintptr_t dest_addr = (uintptr_t) dest; 4 uintptr_t offset = dest_addr % sizeof(jint); 5 volatile jint*dest_int = ( volatile jint*)(dest_addr - offset); 6 // 对象当前值 7 jint cur = *dest_int; 8 // 当前值cur的地址 9 jbyte * cur_as_bytes = (jbyte *) ( & cur); 10 // new_val地址 11 jint new_val = cur; 12 jbyte * new_val_as_bytes = (jbyte *) ( & new_val); 13 // new_val存exchange_value,后面修改则直接从new_val中取值 14 new_val_as_bytes[offset] = exchange_value; 15 // 比较当前值与期望值,如果相同则更新,不同则直接返回 16 while (cur_as_bytes[offset] == compare_value) { 17 // 调用汇编指令cmpxchg执行CAS操作,期望值为cur,更新值为new_val 18 jint res = cmpxchg(new_val, dest_int, cur); 19 if (res == cur) break; 20 cur = res; 21 new_val = cur; 22 new_val_as_bytes[offset] = exchange_value; 23 } 24 // 返回当前值 25 return cur_as_bytes[offset]; 26 }
1 // 类的定义: 2 public class AtomicStampedReference<V> 3 // 构造函数,将对象和标记值传入 4 public AtomicStampedReference(V initialRef, int initialStamp) { 5 pair = Pair.of(initialRef, initialStamp); 6 } 7 // 参数代表的含义分别是 期望值,写入的新值,期望标记,新标记值 8 public boolean compareAndSet(V expectedReference, 9 V newReference, 10 int expectedStamp, 11 int newStamp) { 12 Pair<V> current = pair; 13 // 比较原对象的同时比较版本号是否也相同,如果都相同则进行pair的cas操作 14 return 15 expectedReference == current.reference && 16 expectedStamp == current.stamp && 17 ((newReference == current.reference && 18 newStamp == current.stamp) || 19 casPair(current, Pair.of(newReference, newStamp))); 20 } 21 // 如果在这之前已经有线程对pair进行更新,则会执行失败 22 private boolean casPair(Pair<V> cmp, Pair<V> val) { 23 return UNSAFE.compareAndSwapObject(this, pairOffset, cmp, val); 24 } 25 public V getRerference(); 26 public int getStamp(); 27 public void set(V newReference,int newStamp);
标签:wapi cpu asp pen 加载 版本 api var 交换
原文地址:https://www.cnblogs.com/ningbing/p/14553400.html