AtomicBoolean没有negate()方法吗?

java.util.concurrent.atomic.AtomicBoolean没有一个可以primefaces地否定/反转该值的方法吗? 我可以用另一种方式吗? 我错过了什么吗?

有点老……但并没有真正感觉到答案很棒。

必须完全不同意这不是常见的或仅在硬件中有用。 您可能需要多个线程在单个变量上切换具有相同的可能性…我使用AtomicLong来制作假布尔值。 这是从JMS MessageListener采用的,我需要一半时间响应特定消息而另一半响应另一半。

 public class Mock { private static AtomicLong count = new AtomicLong(0); public boolean respond() { long currentCount = count.getAndIncrement(); if (currentCount % 2 == 0) { return true; } else { return false; } } } 

我天真的实现是这样的:

 boolean v; do { v=atomicBoolean.get(); } while(!atomicBoolean.compareAndSet(v, !v)); 

“ CERT Oracle安全编码标准Java ”一书中提出的解决方案如下:

 import java.util.concurrent.atomic.AtomicBoolean; final class Flag { private AtomicBoolean flag = new AtomicBoolean(true); public void toggle() { boolean temp; do { temp = flag.get(); } while(!flag.compareAndSet(temp, !temp)); } } 

您可以使用AtomicInteger.getAndIncrement()模拟AtomicBoolean.negate() ,并将偶数作为true数和奇数作为false 。 应忽略该数字的实际值,因此您不必关心整数溢出。

使用AtomicBoolean#compareAndSet()方法和while循环,您可以实现一种方法,以线程安全的方式切换AtomicBoolean的值,如下所示:

 public static boolean negate(AtomicBoolean ab) { // get the oposite value boolean newVal = !ab.get(); // try to set the new value if the current value is the oposite of the new value while (!ab.compareAndSet(!newVal, newVal)) { // if the value we try to set was already set in the mean-time // then toggle the new value and try again newVal = !newVal; } // return the value we finally could set return newVal; }