CAS
CAS(Compare And Swap)是一種無鎖原子操作。具體是對比內存中的值與當前線程中我們預期的值,如果一致,則進行下一步賦值,即swap;如果不一致,則采取其他策略。
CAS主要使用Unsafe這個類實現(xiàn)。在Java 9以后VarHandler也可以實現(xiàn)類似功能。這兩個類都通過native的方法實現(xiàn)了CAS的方法。
CAS在Java中有很多應用,下面我們以AtomicBoolean為例,看看他是如何使用的。
AtomicBoolean
public class AtomicInteger extends Number implements java.io.Serializable {
/*
* This class intended to be implemented using VarHandles, but there
* are unresolved cyclic startup dependencies.
*/
private static final jdk.internal.misc.Unsafe U = jdk.internal.misc.Unsafe.getUnsafe();
//通過Unsafe拿到了這個類中的value并拿到偏移量
private static final long VALUE = U.objectFieldOffset(AtomicInteger.class, "value");
private volatile int value;
/**
* Atomically sets the value to {@code newValue}
* if the current value {@code == expectedValue},
* with memory effects as specified by {@link VarHandle#compareAndSet}.
*
* @param expectedValue the expected value
* @param newValue the new value
* @return {@code true} if successful. False return indicates that
* the actual value was not equal to the expected value.
*/
public final boolean compareAndSet(int expectedValue, int newValue) {
//對比預期值如果一致就將心智賦值進入,原子操作
return U.compareAndSetInt(this, VALUE, expectedValue, newValue);
}
}
Android多線程(一)
Android多線程(二)
Android多線程(三)
Android多線程(四)
Android多線程(五)