问题描述
举个例子:
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。