View Javadoc
1   /*
2    * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
3    *
4    * This code is free software; you can redistribute it and/or modify it
5    * under the terms of the GNU General Public License version 2 only, as
6    * published by the Free Software Foundation.  Oracle designates this
7    * particular file as subject to the "Classpath" exception as provided
8    * by Oracle in the LICENSE file that accompanied this code.
9    *
10   * This code is distributed in the hope that it will be useful, but WITHOUT
11   * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
12   * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
13   * version 2 for more details (a copy is included in the LICENSE file that
14   * accompanied this code).
15   *
16   * You should have received a copy of the GNU General Public License version
17   * 2 along with this work; if not, write to the Free Software Foundation,
18   * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
19   *
20   * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
21   * or visit www.oracle.com if you need additional information or have any
22   * questions.
23   */
24  
25  /*
26   * This file is available under and governed by the GNU General Public
27   * License version 2 only, as published by the Free Software Foundation.
28   * However, the following notice accompanied the original version of this
29   * file:
30   *
31   * Written by Doug Lea with assistance from members of JCP JSR-166
32   * Expert Group and released to the public domain, as explained at
33   * http://creativecommons.org/publicdomain/zero/1.0/
34   */
35  
36  package java.util.concurrent.atomic;
37  import sun.misc.Unsafe;
38  
39  /**
40   * A {@code boolean} value that may be updated atomically. See the
41   * {@link java.util.concurrent.atomic} package specification for
42   * description of the properties of atomic variables. An
43   * {@code AtomicBoolean} is used in applications such as atomically
44   * updated flags, and cannot be used as a replacement for a
45   * {@link java.lang.Boolean}.
46   *
47   * @since 1.5
48   * @author Doug Lea
49   */
50  public class AtomicBoolean implements java.io.Serializable {
51      private static final long serialVersionUID = 4654671469794556979L;
52      // setup to use Unsafe.compareAndSwapInt for updates
53      private static final Unsafe unsafe = Unsafe.getUnsafe();
54      private static final long valueOffset;
55  
56      static {
57          try {
58              valueOffset = unsafe.objectFieldOffset
59                  (AtomicBoolean.class.getDeclaredField("value"));
60          } catch (Exception ex) { throw new Error(ex); }
61      }
62  
63      private volatile int value;
64  
65      /**
66       * Creates a new {@code AtomicBoolean} with the given initial value.
67       *
68       * @param initialValue the initial value
69       */
70      public AtomicBoolean(boolean initialValue) {
71          value = initialValue ? 1 : 0;
72      }
73  
74      /**
75       * Creates a new {@code AtomicBoolean} with initial value {@code false}.
76       */
77      public AtomicBoolean() {
78      }
79  
80      /**
81       * Returns the current value.
82       *
83       * @return the current value
84       */
85      public final boolean get() {
86          return value != 0;
87      }
88  
89      /**
90       * Atomically sets the value to the given updated value
91       * if the current value {@code ==} the expected value.
92       *
93       * @param expect the expected value
94       * @param update the new value
95       * @return {@code true} if successful. False return indicates that
96       * the actual value was not equal to the expected value.
97       */
98      public final boolean compareAndSet(boolean expect, boolean update) {
99          int e = expect ? 1 : 0;
100         int u = update ? 1 : 0;
101         return unsafe.compareAndSwapInt(this, valueOffset, e, u);
102     }
103 
104     /**
105      * Atomically sets the value to the given updated value
106      * if the current value {@code ==} the expected value.
107      *
108      * <p><a href="package-summary.html#weakCompareAndSet">May fail
109      * spuriously and does not provide ordering guarantees</a>, so is
110      * only rarely an appropriate alternative to {@code compareAndSet}.
111      *
112      * @param expect the expected value
113      * @param update the new value
114      * @return {@code true} if successful
115      */
116     public boolean weakCompareAndSet(boolean expect, boolean update) {
117         int e = expect ? 1 : 0;
118         int u = update ? 1 : 0;
119         return unsafe.compareAndSwapInt(this, valueOffset, e, u);
120     }
121 
122     /**
123      * Unconditionally sets to the given value.
124      *
125      * @param newValue the new value
126      */
127     public final void set(boolean newValue) {
128         value = newValue ? 1 : 0;
129     }
130 
131     /**
132      * Eventually sets to the given value.
133      *
134      * @param newValue the new value
135      * @since 1.6
136      */
137     public final void lazySet(boolean newValue) {
138         int v = newValue ? 1 : 0;
139         unsafe.putOrderedInt(this, valueOffset, v);
140     }
141 
142     /**
143      * Atomically sets to the given value and returns the previous value.
144      *
145      * @param newValue the new value
146      * @return the previous value
147      */
148     public final boolean getAndSet(boolean newValue) {
149         boolean prev;
150         do {
151             prev = get();
152         } while (!compareAndSet(prev, newValue));
153         return prev;
154     }
155 
156     /**
157      * Returns the String representation of the current value.
158      * @return the String representation of the current value
159      */
160     public String toString() {
161         return Boolean.toString(get());
162     }
163 
164 }