/** compareAndSet succeeds in changing value if equal to expected else fails */ public void testCompareAndSet() { AtomicLong ai = new AtomicLong(1); assertTrue(ai.compareAndSet(1, 2)); assertTrue(ai.compareAndSet(2, -4)); assertEquals(-4, ai.get()); assertFalse(ai.compareAndSet(-5, 7)); assertFalse((7 == ai.get())); assertTrue(ai.compareAndSet(-4, 7)); assertEquals(7, ai.get()); }
/** compareAndSet in one thread enables another waiting for value to succeed */ public void testCompareAndSetInMultipleThreads() { final AtomicLong ai = new AtomicLong(1); Thread t = new Thread( new Runnable() { public void run() { while (!ai.compareAndSet(2, 3)) Thread.yield(); } }); try { t.start(); assertTrue(ai.compareAndSet(1, 2)); t.join(LONG_DELAY_MS); assertFalse(t.isAlive()); assertEquals(ai.get(), 3); } catch (Exception e) { unexpectedException(); } }