如何在AtomicInteger
變量中執行「check-then-act」?
I.e.什麼是最安全/最好的方法來檢查這種變量的值第一個和inc/dec取決於結果?
例如(高級別)
if(count < VALUE) count++;
//原子級使用AtomicInteger
安全地使用AtomicInteger首先檢查
4
A
回答
10
您需要編寫一個循環。假設count
是你AtomicInteger
參考,你會寫是這樣的:
while(true)
{
final int oldCount = count.get();
if(oldCount >= VALUE)
break;
if(count.compareAndSet(oldCount, oldCount + 1))
break;
}
上面會循環,直到:(1)你的if(count < VALUE)
條件未得到滿足;或(2)count
成功遞增。使用compareAndSet
執行增量操作可以保證當我們設置新值時,count
的值仍然是oldCount
(因此仍然小於VALUE
)。
0
如果你使用Java 8,你可以像這樣解決它。它是線程安全的並且是以原子方式執行的。
AtomicInteger counter = new AtomicInteger();
static final int COUNT = 10;
public int incrementUntilLimitReached() {
return counter.getAndUpdate((n -> (n < COUNT) ? n + 1 : n));
}
相關問題
- 1. 使用Try Catch或首先檢查值
- 2. 安全地推入git而不是首先獲取? (或git pull)
- 3. 委派線程安全ConcurrentMap和的AtomicInteger
- 4. 首先檢查安裝和註冊表值維克斯
- 5. 安全地檢查'this`是否爲空
- 6. 首先檢查時間戳嗎?
- 7. 使用MD5和鹽j安全檢查
- 8. 如何安全地使用Jquery檢查屬性值?
- 9. 安全地使用pathlib檢查子文件夾
- 10. 全部選項首先
- 11. 使用Javascript安全地查詢Solr
- 12. Grails安全檢查
- 13. Java首選項本地安全存儲
- 14. LibGDX - 安全地使用「首選項」存儲高分
- 15. 服務引用安全首
- 16. 如何修改此活動記錄查詢以首先檢查完全匹配?
- 17. ASP.Net MVC:IAuthorizationFilter /屬性首選安全檢查登錄?
- 18. 安全地檢索密鑰
- 19. 如何使用AtomicInteger?
- 20. 安全地修改std :: pair <U, V> ::首先在對的向量?
- 21. 春季安全登錄2FA - 首先檢查用戶名和密碼,然後根據需要詢問2FA代碼
- 22. Freemarker的空例外,即使檢查它首先
- 23. 播放幀首先使用
- 24. 燒瓶安全:SMTPServerDisconnected:請首先運行connect()
- 25. 安全會話檢查
- 26. ASP/Javascript onClientClick安全檢查()
- 27. PHP會話安全檢查
- 28. PHP安全會話檢查?
- 29. PHP fuzzer安全檢查(Radamsa)
- 30. 是http_x_forwarded_for安全檢查IP
http://stackoverflow.com/questions/4818699/practical-uses-for-atomicinteger – user219882 2012-03-30 11:26:50
@Tomas:我沒有看到一個答案在你link.Only如何使用it.How可以我原子地做一個check-then-act? – Jim 2012-03-30 11:31:12