[英]Is AtomicInteger fair?
不,沒有這樣的保證。 如果有的話,將在文檔中詳細說明。
當你考慮它時, AtomicInteger
基本上是比較和交換 (或類似)的薄包裝。 保證先來先服務語義需要線程之間的同步,這是昂貴的,並且與AtomicInteger
想法相反。
事情的方式是,如果有多個線程想要,例如, incrementAndGet()
同時使用相同的原子整數,那么它們完成比賽的順序是未指定的。
與你可能做的任何事情相比,它的運作速度非常快。 這意味着您極不可能獲得爭用,因此公平性不太可能成為問題。
如果你稱它為20億次(你可以在幾秒鍾內完成),它無論如何都會過度流動。 如果這是一個問題,我會使用AtomicLong。
如果您查看來源,您將得到正確的答案,即YES和NO有關訂購保證。 這取決於被調用的方法。 有些支持訂購保證,有些則沒有。
以下源代碼表明它支持兩種模式,具體取決於調用哪種方法。
138 /**
139 * Atomically sets the value to the given updated value
140 * if the current value {@code ==} the expected value.
141 *
142 * <p>May <a href="package-summary.html#Spurious">fail spuriously</a>
143 * and does not provide ordering guarantees, so is only rarely an
144 * appropriate alternative to {@code compareAndSet}.
145 *
146 * @param expect the expected value
147 * @param update the new value
148 * @return true if successful.
149 */
150 public final boolean weakCompareAndSet(int expect, int update) {
151 return unsafe.compareAndSwapInt(this, valueOffset, expect, update);
152 }
如有疑問,請閱讀JavaDoc,如果還不清楚,請閱讀源代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.