/** repeated weakCompareAndSet succeeds in changing value when equal to expected */
 public void testWeakCompareAndSet() {
   AtomicInteger ai = new AtomicInteger(1);
   do {} while (!ai.weakCompareAndSet(1, 2));
   do {} while (!ai.weakCompareAndSet(2, -4));
   assertEquals(-4, ai.get());
   do {} while (!ai.weakCompareAndSet(-4, 7));
   assertEquals(7, ai.get());
 }
Example #2
0
 /** 1. 如果当前值 == 预期值,则以原子方式将该设置为给定的更新值。 2. 可能意外失败并且不提供排序保证,所以只有在很少的情况下才对 compareAndSet 进行适当地选择。 */
 public void testWeakCompareAndSet() {
   AtomicInteger ai = new AtomicInteger();
   int expect = 0;
   int update = 0;
   do {
     expect = ai.get();
     update = expect + 10;
   } while (!ai.weakCompareAndSet(expect, update));
   System.out.println(ai.get());
 }
  private void perf2(AtomicInteger count) {
    long startMillis = System.currentTimeMillis();

    count.set(0);
    for (int i = 0; i < 1000 * 1000 * 100; ++i) {
      int value = count.get();
      count.weakCompareAndSet(value, value + 1);
    }

    long millis = System.currentTimeMillis() - startMillis;
    System.out.println("weak millis " + millis);
  }
Example #4
0
 /**
  * Atomically set this reduction variable to the given updated value if the current value equals
  * the expected value. May fail spuriously.
  *
  * @param expect Expected value.
  * @param update Updated value.
  * @return True if the update happened, false otherwise.
  */
 public boolean weakCompareAndSet(int expect, int update) {
   return myValue.weakCompareAndSet(expect, update);
 }