又想到一种,既然两个变量要同时锁定,那就把两个变量封装成一个,然后使用cas操作。这样行不行,另外老师帮我看看volatile是不是有多余的地方
···········
volatile AtomicReference<Inventory> inventory = new AtomicReference<>();
static class Inventory {
private volatile long upper = 0;
private volatile long lower = 0;
}
void setUpper(long v) {
long low;
Inventory oldObj;
Inventory newObj;
do {
oldObj = inventory.get();
if (v >= (low = oldObj.lower)) {
throw new IllegalArgumentException();
}
newObj = new Inventory();
newObj.lower = low;
newObj.upper = v;
} while (inventory.compareAndSet(oldObj, newObj));
}
void setLower(long v) {
long upp;
Inventory oldObj;
Inventory newObj;
do {
oldObj = inventory.get();
if (v <= (upp = oldObj.upper)) {
throw new IllegalArgumentException();
}
newObj = new Inventory();
newObj.lower = v;
newObj.upper = upp;
} while (inventory.compareAndSet(oldObj, newObj));
}
展开
作者回复: 我觉得这个没有问题,volatile 换成 final会更好