8162805: Optimize AtomicBoolean.getAndSet
authordl
Mon, 15 Aug 2016 09:04:40 -0700
changeset 40277 fd3c777aed08
parent 40276 2217f830ca7b
child 40278 8801563939d0
8162805: Optimize AtomicBoolean.getAndSet Reviewed-by: martin, psandoz, shade
jdk/src/java.base/share/classes/java/util/concurrent/atomic/AtomicBoolean.java
jdk/test/java/util/concurrent/tck/AtomicBooleanTest.java
--- a/jdk/src/java.base/share/classes/java/util/concurrent/atomic/AtomicBoolean.java	Mon Aug 15 14:25:51 2016 +0100
+++ b/jdk/src/java.base/share/classes/java/util/concurrent/atomic/AtomicBoolean.java	Mon Aug 15 09:04:40 2016 -0700
@@ -147,11 +147,7 @@
      * @return the previous value
      */
     public final boolean getAndSet(boolean newValue) {
-        boolean prev;
-        do {
-            prev = get();
-        } while (!compareAndSet(prev, newValue));
-        return prev;
+        return (int)VALUE.getAndSet(this, (newValue ? 1 : 0)) != 0;
     }
 
     /**
--- a/jdk/test/java/util/concurrent/tck/AtomicBooleanTest.java	Mon Aug 15 14:25:51 2016 +0100
+++ b/jdk/test/java/util/concurrent/tck/AtomicBooleanTest.java	Mon Aug 15 09:04:40 2016 -0700
@@ -136,11 +136,14 @@
      * getAndSet returns previous value and sets to given value
      */
     public void testGetAndSet() {
-        AtomicBoolean ai = new AtomicBoolean(true);
-        assertEquals(true, ai.getAndSet(false));
-        assertEquals(false, ai.getAndSet(false));
-        assertEquals(false, ai.getAndSet(true));
-        assertTrue(ai.get());
+        AtomicBoolean ai = new AtomicBoolean();
+        boolean[] booleans = { false, true };
+        for (boolean before : booleans)
+            for (boolean after : booleans) {
+                ai.set(before);
+                assertEquals(before, ai.getAndSet(after));
+                assertEquals(after, ai.get());
+            }
     }
 
     /**