[英]Is there a way to implement an if-else condition that is threadsafe/ atomic in java?
讓我們舉個例子:
public class XYZ{
private AtomicInteger var1;
private int const_val;
// these all attributes are initialized with a constructor, when an instance of the class is called.
// my focus is on this method, to make this thread-safe
public boolean isPossible(){
if(var1 < const_val){
var1.incrementAndGet();
return true;
}
else{
return false;
}
}
}
如果我不能使用鎖定機制(在java中),如何使這個(整個“if-else”片段)線程安全/原子?
我在 AtomicIntegers 上讀了一些東西,並用 AtomicBooleans 讀了一些東西,我可以使用這些來使這個片段線程安全嗎?
像這樣的東西應該可以解決問題。
public boolean isPossible(){
for(;;){
int current = var1.get();
if(current>=max){
return false;
}
if(var1.compareAndSet(current, current+1)){
return true;
}
}
}
除了在寫入時強制執行最大值,您可以無條件地遞增,並在讀取時強制執行最大值,如下所示:
public boolean increment(){
return var1.getAndIncrement() < const_val;
}
public int getVar1() {
return Math.min(const_val, var1.get());
}
這是假設你對這個變量所做的只是增加它。 此解決方案的一個問題是它最終可能導致溢出。 如果這可能是一個問題,您可以切換到 AtomicLong。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.