KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > java > util > concurrent > atomic > AtomicIntegerFieldUpdater


1 /*
2  * @(#)AtomicIntegerFieldUpdater.java 1.7 05/08/09
3  *
4  * Copyright 2005 Sun Microsystems, Inc. All rights reserved.
5  * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
6  */

7
8 package java.util.concurrent.atomic;
9 import sun.misc.Unsafe;
10 import java.lang.reflect.*;
11
12 /**
13  * A reflection-based utility that enables atomic updates to
14  * designated <tt>volatile int</tt> fields of designated classes.
15  * This class is designed for use in atomic data structures in which
16  * several fields of the same node are independently subject to atomic
17  * updates.
18  *
19  * <p> Note that the guarantees of the <tt>compareAndSet</tt> method
20  * in this class are weaker than in other atomic classes. Because this
21  * class cannot ensure that all uses of the field are appropriate for
22  * purposes of atomic access, it can guarantee atomicity and volatile
23  * semantics only with respect to other invocations of
24  * <tt>compareAndSet</tt> and <tt>set</tt>.
25  * @since 1.5
26  * @author Doug Lea
27  * @param <T> The type of the object holding the updatable field
28  */

29 public abstract class AtomicIntegerFieldUpdater<T> {
30     /**
31      * Creates an updater for objects with the given field. The Class
32      * argument is needed to check that reflective types and generic
33      * types match.
34      * @param tclass the class of the objects holding the field
35      * @param fieldName the name of the field to be updated.
36      * @return the updater
37      * @throws IllegalArgumentException if the field is not a
38      * volatile integer type.
39      * @throws RuntimeException with a nested reflection-based
40      * exception if the class does not hold field or is the wrong type.
41      */

42     public static <U> AtomicIntegerFieldUpdater JavaDoc<U> newUpdater(Class JavaDoc<U> tclass, String JavaDoc fieldName) {
43         return new AtomicIntegerFieldUpdaterImpl<U>(tclass, fieldName);
44     }
45
46     /**
47      * Protected do-nothing constructor for use by subclasses.
48      */

49     protected AtomicIntegerFieldUpdater() {
50     }
51
52     /**
53      * Atomically set the value of the field of the given object managed
54      * by this Updater to the given updated value if the current value
55      * <tt>==</tt> the expected value. This method is guaranteed to be
56      * atomic with respect to other calls to <tt>compareAndSet</tt> and
57      * <tt>set</tt>, but not necessarily with respect to other
58      * changes in the field.
59      * @param obj An object whose field to conditionally set
60      * @param expect the expected value
61      * @param update the new value
62      * @return true if successful.
63      * @throws ClassCastException if <tt>obj</tt> is not an instance
64      * of the class possessing the field established in the constructor.
65      */

66
67     public abstract boolean compareAndSet(T obj, int expect, int update);
68
69     /**
70      * Atomically set the value of the field of the given object managed
71      * by this Updater to the given updated value if the current value
72      * <tt>==</tt> the expected value. This method is guaranteed to be
73      * atomic with respect to other calls to <tt>compareAndSet</tt> and
74      * <tt>set</tt>, but not necessarily with respect to other
75      * changes in the field, and may fail spuriously.
76      * @param obj An object whose field to conditionally set
77      * @param expect the expected value
78      * @param update the new value
79      * @return true if successful.
80      * @throws ClassCastException if <tt>obj</tt> is not an instance
81      * of the class possessing the field established in the constructor.
82      */

83
84     public abstract boolean weakCompareAndSet(T obj, int expect, int update);
85
86     /**
87      * Set the field of the given object managed by this updater. This
88      * operation is guaranteed to act as a volatile store with respect
89      * to subsequent invocations of <tt>compareAndSet</tt>.
90      * @param obj An object whose field to set
91      * @param newValue the new value
92      */

93     public abstract void set(T obj, int newValue);
94
95     /**
96      * Get the current value held in the field by the given object.
97      * @param obj An object whose field to get
98      * @return the current value
99      */

100     public abstract int get(T obj);
101
102     /**
103      * Set to the given value and return the old value.
104      *
105      * @param obj An object whose field to get and set
106      * @param newValue the new value
107      * @return the previous value
108      */

109     public int getAndSet(T obj, int newValue) {
110         for (;;) {
111             int current = get(obj);
112             if (compareAndSet(obj, current, newValue))
113                 return current;
114         }
115     }
116
117     /**
118      * Atomically increment by one the current value.
119      * @param obj An object whose field to get and set
120      * @return the previous value;
121      */

122     public int getAndIncrement(T obj) {
123         for (;;) {
124             int current = get(obj);
125             int next = current + 1;
126             if (compareAndSet(obj, current, next))
127                 return current;
128         }
129     }
130
131
132     /**
133      * Atomically decrement by one the current value.
134      * @param obj An object whose field to get and set
135      * @return the previous value;
136      */

137     public int getAndDecrement(T obj) {
138         for (;;) {
139             int current = get(obj);
140             int next = current - 1;
141             if (compareAndSet(obj, current, next))
142                 return current;
143         }
144     }
145
146
147     /**
148      * Atomically add the given value to current value.
149      * @param obj An object whose field to get and set
150      * @param delta the value to add
151      * @return the previous value;
152      */

153     public int getAndAdd(T obj, int delta) {
154         for (;;) {
155             int current = get(obj);
156             int next = current + delta;
157             if (compareAndSet(obj, current, next))
158                 return current;
159         }
160     }
161
162     /**
163      * Atomically increment by one the current value.
164      * @param obj An object whose field to get and set
165      * @return the updated value;
166      */

167     public int incrementAndGet(T obj) {
168         for (;;) {
169             int current = get(obj);
170             int next = current + 1;
171             if (compareAndSet(obj, current, next))
172                 return next;
173         }
174     }
175
176
177     /**
178      * Atomically decrement by one the current value.
179      * @param obj An object whose field to get and set
180      * @return the updated value;
181      */

182     public int decrementAndGet(T obj) {
183         for (;;) {
184             int current = get(obj);
185             int next = current - 1;
186             if (compareAndSet(obj, current, next))
187                 return next;
188         }
189     }
190
191
192     /**
193      * Atomically add the given value to current value.
194      * @param obj An object whose field to get and set
195      * @param delta the value to add
196      * @return the updated value;
197      */

198     public int addAndGet(T obj, int delta) {
199         for (;;) {
200             int current = get(obj);
201             int next = current + delta;
202             if (compareAndSet(obj, current, next))
203                 return next;
204         }
205     }
206
207     /**
208      * Standard hotspot implementation using intrinsics
209      */

210     private static class AtomicIntegerFieldUpdaterImpl<T> extends AtomicIntegerFieldUpdater JavaDoc<T> {
211         private static final Unsafe unsafe = Unsafe.getUnsafe();
212         private final long offset;
213         private final Class JavaDoc<T> tclass;
214         private final Class JavaDoc cclass;
215
216         AtomicIntegerFieldUpdaterImpl(Class JavaDoc<T> tclass, String JavaDoc fieldName) {
217             Field field = null;
218         Class JavaDoc caller = null;
219         int modifiers = 0;
220             try {
221                 field = tclass.getDeclaredField(fieldName);
222         caller = sun.reflect.Reflection.getCallerClass(3);
223         modifiers = field.getModifiers();
224                 sun.reflect.misc.ReflectUtil.ensureMemberAccess(
225                     caller, tclass, null, modifiers);
226         sun.reflect.misc.ReflectUtil.checkPackageAccess(tclass);
227             } catch(Exception JavaDoc ex) {
228                 throw new RuntimeException JavaDoc(ex);
229             }
230
231             Class JavaDoc fieldt = field.getType();
232             if (fieldt != int.class)
233                 throw new IllegalArgumentException JavaDoc("Must be integer type");
234             
235             if (!Modifier.isVolatile(modifiers))
236                 throw new IllegalArgumentException JavaDoc("Must be volatile type");
237          
238         this.cclass = (Modifier.isProtected(modifiers) &&
239                caller != tclass) ? caller : null;
240             this.tclass = tclass;
241             offset = unsafe.objectFieldOffset(field);
242         }
243
244         public boolean compareAndSet(T obj, int expect, int update) {
245             if (!tclass.isInstance(obj))
246                 throw new ClassCastException JavaDoc();
247         if (cclass != null)
248             ensureProtectedAccess(obj);
249             return unsafe.compareAndSwapInt(obj, offset, expect, update);
250         }
251
252         public boolean weakCompareAndSet(T obj, int expect, int update) {
253             if (!tclass.isInstance(obj))
254                 throw new ClassCastException JavaDoc();
255         if (cclass != null)
256             ensureProtectedAccess(obj);
257             return unsafe.compareAndSwapInt(obj, offset, expect, update);
258         }
259
260         public void set(T obj, int newValue) {
261             if (!tclass.isInstance(obj))
262                 throw new ClassCastException JavaDoc();
263         if (cclass != null)
264             ensureProtectedAccess(obj);
265             unsafe.putIntVolatile(obj, offset, newValue);
266         }
267
268         public final int get(T obj) {
269             if (!tclass.isInstance(obj))
270                 throw new ClassCastException JavaDoc();
271         if (cclass != null)
272             ensureProtectedAccess(obj);
273             return unsafe.getIntVolatile(obj, offset);
274         }
275
276     private void ensureProtectedAccess(T obj) {
277         if (cclass.isInstance(obj)) {
278         return;
279         }
280         throw new RuntimeException JavaDoc(
281                 new IllegalAccessException JavaDoc("Class " +
282             cclass.getName() +
283                     " can not access a protected member of class " +
284                     tclass.getName() +
285             " using an instance of " +
286                     obj.getClass().getName()
287         )
288         );
289     }
290     }
291 }
292
293
Popular Tags