# HG changeset patch # User dl # Date 1471277080 25200 # Node ID fd3c777aed0838a18c4d467840d3a4dbc5e5072c # Parent 2217f830ca7b67c00c2a1b3dc83979fc24d3aa98 8162805: Optimize AtomicBoolean.getAndSet Reviewed-by: martin, psandoz, shade diff -r 2217f830ca7b -r fd3c777aed08 jdk/src/java.base/share/classes/java/util/concurrent/atomic/AtomicBoolean.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; } /** diff -r 2217f830ca7b -r fd3c777aed08 jdk/test/java/util/concurrent/tck/AtomicBooleanTest.java --- 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()); + } } /**