< prev index next >

src/java.base/share/classes/java/lang/ThreadLocal.java

Print this page

  7  * published by the Free Software Foundation.  Oracle designates this
  8  * particular file as subject to the "Classpath" exception as provided
  9  * by Oracle in the LICENSE file that accompanied this code.
 10  *
 11  * This code is distributed in the hope that it will be useful, but WITHOUT
 12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 14  * version 2 for more details (a copy is included in the LICENSE file that
 15  * accompanied this code).
 16  *
 17  * You should have received a copy of the GNU General Public License version
 18  * 2 along with this work; if not, write to the Free Software Foundation,
 19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 20  *
 21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 22  * or visit www.oracle.com if you need additional information or have any
 23  * questions.
 24  */
 25 
 26 package java.lang;
 27 import jdk.internal.misc.TerminatingThreadLocal;
 28 
 29 import java.lang.ref.WeakReference;
 30 import java.util.Objects;
 31 import java.util.concurrent.atomic.AtomicInteger;
 32 import java.util.function.Supplier;
 33 


 34 /**
 35  * This class provides thread-local variables.  These variables differ from
 36  * their normal counterparts in that each thread that accesses one (via its
 37  * {@code get} or {@code set} method) has its own, independently initialized
 38  * copy of the variable.  {@code ThreadLocal} instances are typically private
 39  * static fields in classes that wish to associate state with a thread (e.g.,
 40  * a user ID or Transaction ID).
 41  *
 42  * <p>For example, the class below generates unique identifiers local to each
 43  * thread.
 44  * A thread's id is assigned the first time it invokes {@code ThreadId.get()}
 45  * and remains unchanged on subsequent calls.
 46  * <pre>
 47  * import java.util.concurrent.atomic.AtomicInteger;
 48  *
 49  * public class ThreadId {
 50  *     // Atomic integer containing the next thread ID to be assigned
 51  *     private static final AtomicInteger nextId = new AtomicInteger(0);
 52  *
 53  *     // Thread local variable containing each thread's ID

 86      */
 87     private final int threadLocalHashCode = nextHashCode();
 88 
 89     /**
 90      * The next hash code to be given out. Updated atomically. Starts at
 91      * zero.
 92      */
 93     private static AtomicInteger nextHashCode =
 94         new AtomicInteger();
 95 
 96     /**
 97      * The difference between successively generated hash codes - turns
 98      * implicit sequential thread-local IDs into near-optimally spread
 99      * multiplicative hash values for power-of-two-sized tables.
100      */
101     private static final int HASH_INCREMENT = 0x61c88647;
102 
103     /**
104      * Returns the next hash code.
105      */
106     private static int nextHashCode() {
107         return nextHashCode.getAndAdd(HASH_INCREMENT);
108     }
109 
110     /**
111      * Returns the current thread's "initial value" for this
112      * thread-local variable.  This method will be invoked the first
113      * time a thread accesses the variable with the {@link #get}
114      * method, unless the thread previously invoked the {@link #set}
115      * method, in which case the {@code initialValue} method will not
116      * be invoked for the thread.  Normally, this method is invoked at
117      * most once per thread, but it may be invoked again in case of
118      * subsequent invocations of {@link #remove} followed by {@link #get}.
119      *
120      * <p>This implementation simply returns {@code null}; if the
121      * programmer desires thread-local variables to have an initial
122      * value other than {@code null}, {@code ThreadLocal} must be
123      * subclassed, and this method overridden.  Typically, an
124      * anonymous inner class will be used.
125      *
126      * @return the initial value for this thread-local

138      * @return a new thread local variable
139      * @throws NullPointerException if the specified supplier is null
140      * @since 1.8
141      */
142     public static <S> ThreadLocal<S> withInitial(Supplier<? extends S> supplier) {
143         return new SuppliedThreadLocal<>(supplier);
144     }
145 
146     /**
147      * Creates a thread local variable.
148      * @see #withInitial(java.util.function.Supplier)
149      */
150     public ThreadLocal() {
151     }
152 
153     /**
154      * Returns the value in the current thread's copy of this
155      * thread-local variable.  If the variable has no value for the
156      * current thread, it is first initialized to the value returned
157      * by an invocation of the {@link #initialValue} method.



158      *
159      * @return the current thread's value of this thread-local

160      */
161     public T get() {
162         Thread t = Thread.currentThread();











163         ThreadLocalMap map = getMap(t);
164         if (map != null) {
165             ThreadLocalMap.Entry e = map.getEntry(this);
166             if (e != null) {
167                 @SuppressWarnings("unchecked")
168                 T result = (T)e.value;
169                 return result;
170             }
171         }
172         return setInitialValue();
173     }
174 
175     /**
176      * Returns {@code true} if there is a value in the current thread's copy of
177      * this thread-local variable, even if that values is {@code null}.
178      *
179      * @return {@code true} if current thread has associated value in this
180      *         thread-local variable; {@code false} if not
181      */
182     boolean isPresent() {
183         Thread t = Thread.currentThread();
184         ThreadLocalMap map = getMap(t);
185         return map != null && map.getEntry(this) != null;




186     }
187 
188     /**
189      * Variant of set() to establish initialValue. Used instead
190      * of set() in case user has overridden the set() method.
191      *
192      * @return the initial value
193      */
194     private T setInitialValue() {
195         T value = initialValue();
196         Thread t = Thread.currentThread();
197         ThreadLocalMap map = getMap(t);



198         if (map != null) {
199             map.set(this, value);
200         } else {
201             createMap(t, value);
202         }
203         if (this instanceof TerminatingThreadLocal) {
204             TerminatingThreadLocal.register((TerminatingThreadLocal<?>) this);
205         }
206         return value;
207     }
208 
209     /**
210      * Sets the current thread's copy of this thread-local variable
211      * to the specified value.  Most subclasses will have no need to
212      * override this method, relying solely on the {@link #initialValue}
213      * method to set the values of thread-locals.
214      *
215      * @param value the value to be stored in the current thread's copy of
216      *        this thread-local.





217      */
218     public void set(T value) {
219         Thread t = Thread.currentThread();







220         ThreadLocalMap map = getMap(t);



221         if (map != null) {
222             map.set(this, value);
223         } else {
224             createMap(t, value);
225         }
226     }
227 
228     /**
229      * Removes the current thread's value for this thread-local
230      * variable.  If this thread-local variable is subsequently
231      * {@linkplain #get read} by the current thread, its value will be
232      * reinitialized by invoking its {@link #initialValue} method,
233      * unless its value is {@linkplain #set set} by the current thread
234      * in the interim.  This may result in multiple invocations of the
235      * {@code initialValue} method in the current thread.
236      *
237      * @since 1.5
238      */
239      public void remove() {
240          ThreadLocalMap m = getMap(Thread.currentThread());
241          if (m != null) {
242              m.remove(this);
243          }
244      }
245 
246     /**
247      * Get the map associated with a ThreadLocal. Overridden in
248      * InheritableThreadLocal.
249      *
250      * @param  t the current thread
251      * @return the map
252      */
253     ThreadLocalMap getMap(Thread t) {
254         return t.threadLocals;
255     }
256 
257     /**
258      * Create the map associated with a ThreadLocal. Overridden in
259      * InheritableThreadLocal.
260      *
261      * @param t the current thread

319     static class ThreadLocalMap {
320 
321         /**
322          * The entries in this hash map extend WeakReference, using
323          * its main ref field as the key (which is always a
324          * ThreadLocal object).  Note that null keys (i.e. entry.get()
325          * == null) mean that the key is no longer referenced, so the
326          * entry can be expunged from table.  Such entries are referred to
327          * as "stale entries" in the code that follows.
328          */
329         static class Entry extends WeakReference<ThreadLocal<?>> {
330             /** The value associated with this ThreadLocal. */
331             Object value;
332 
333             Entry(ThreadLocal<?> k, Object v) {
334                 super(k);
335                 value = v;
336             }
337         }
338 


339         /**
340          * The initial capacity -- MUST be a power of two.
341          */
342         private static final int INITIAL_CAPACITY = 16;
343 
344         /**
345          * The table, resized as necessary.
346          * table.length MUST always be a power of two.
347          */
348         private Entry[] table;
349 
350         /**
351          * The number of entries in the table.
352          */
353         private int size = 0;
354 
355         /**
356          * The next size value at which to resize.
357          */
358         private int threshold; // Default to 0

361          * Set the resize threshold to maintain at worst a 2/3 load factor.
362          */
363         private void setThreshold(int len) {
364             threshold = len * 2 / 3;
365         }
366 
367         /**
368          * Increment i modulo len.
369          */
370         private static int nextIndex(int i, int len) {
371             return ((i + 1 < len) ? i + 1 : 0);
372         }
373 
374         /**
375          * Decrement i modulo len.
376          */
377         private static int prevIndex(int i, int len) {
378             return ((i - 1 >= 0) ? i - 1 : len - 1);
379         }
380 



381         /**
382          * Construct a new map initially containing (firstKey, firstValue).
383          * ThreadLocalMaps are constructed lazily, so we only create
384          * one when we have at least one entry to put in it.
385          */
386         ThreadLocalMap(ThreadLocal<?> firstKey, Object firstValue) {
387             table = new Entry[INITIAL_CAPACITY];
388             int i = firstKey.threadLocalHashCode & (INITIAL_CAPACITY - 1);
389             table[i] = new Entry(firstKey, firstValue);
390             size = 1;
391             setThreshold(INITIAL_CAPACITY);
392         }
393 
394         /**
395          * Construct a new map including all Inheritable ThreadLocals
396          * from given parent map. Called only by createInheritedMap.
397          *
398          * @param parentMap the map associated with parent thread.
399          */
400         private ThreadLocalMap(ThreadLocalMap parentMap) {

403             setThreshold(len);
404             table = new Entry[len];
405 
406             for (Entry e : parentTable) {
407                 if (e != null) {
408                     @SuppressWarnings("unchecked")
409                     ThreadLocal<Object> key = (ThreadLocal<Object>) e.get();
410                     if (key != null) {
411                         Object value = key.childValue(e.value);
412                         Entry c = new Entry(key, value);
413                         int h = key.threadLocalHashCode & (len - 1);
414                         while (table[h] != null)
415                             h = nextIndex(h, len);
416                         table[h] = c;
417                         size++;
418                     }
419                 }
420             }
421         }
422 







423         /**
424          * Get the entry associated with key.  This method
425          * itself handles only the fast path: a direct hit of existing
426          * key. It otherwise relays to getEntryAfterMiss.  This is
427          * designed to maximize performance for direct hits, in part
428          * by making this method readily inlinable.
429          *
430          * @param  key the thread local object
431          * @return the entry associated with key, or null if no such
432          */
433         private Entry getEntry(ThreadLocal<?> key) {
434             int i = key.threadLocalHashCode & (table.length - 1);
435             Entry e = table[i];
436             if (e != null && e.refersTo(key))
437                 return e;
438             else
439                 return getEntryAfterMiss(key, i, e);
440         }
441 
442         /**

  7  * published by the Free Software Foundation.  Oracle designates this
  8  * particular file as subject to the "Classpath" exception as provided
  9  * by Oracle in the LICENSE file that accompanied this code.
 10  *
 11  * This code is distributed in the hope that it will be useful, but WITHOUT
 12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 14  * version 2 for more details (a copy is included in the LICENSE file that
 15  * accompanied this code).
 16  *
 17  * You should have received a copy of the GNU General Public License version
 18  * 2 along with this work; if not, write to the Free Software Foundation,
 19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 20  *
 21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 22  * or visit www.oracle.com if you need additional information or have any
 23  * questions.
 24  */
 25 
 26 package java.lang;

 27 
 28 import java.lang.ref.WeakReference;
 29 import java.util.Objects;
 30 import java.util.concurrent.atomic.AtomicInteger;
 31 import java.util.function.Supplier;
 32 
 33 import jdk.internal.misc.TerminatingThreadLocal;
 34 
 35 /**
 36  * This class provides thread-local variables.  These variables differ from
 37  * their normal counterparts in that each thread that accesses one (via its
 38  * {@code get} or {@code set} method) has its own, independently initialized
 39  * copy of the variable.  {@code ThreadLocal} instances are typically private
 40  * static fields in classes that wish to associate state with a thread (e.g.,
 41  * a user ID or Transaction ID).
 42  *
 43  * <p>For example, the class below generates unique identifiers local to each
 44  * thread.
 45  * A thread's id is assigned the first time it invokes {@code ThreadId.get()}
 46  * and remains unchanged on subsequent calls.
 47  * <pre>
 48  * import java.util.concurrent.atomic.AtomicInteger;
 49  *
 50  * public class ThreadId {
 51  *     // Atomic integer containing the next thread ID to be assigned
 52  *     private static final AtomicInteger nextId = new AtomicInteger(0);
 53  *
 54  *     // Thread local variable containing each thread's ID

 87      */
 88     private final int threadLocalHashCode = nextHashCode();
 89 
 90     /**
 91      * The next hash code to be given out. Updated atomically. Starts at
 92      * zero.
 93      */
 94     private static AtomicInteger nextHashCode =
 95         new AtomicInteger();
 96 
 97     /**
 98      * The difference between successively generated hash codes - turns
 99      * implicit sequential thread-local IDs into near-optimally spread
100      * multiplicative hash values for power-of-two-sized tables.
101      */
102     private static final int HASH_INCREMENT = 0x61c88647;
103 
104     /**
105      * Returns the next hash code.
106      */
107     static int nextHashCode() {
108         return nextHashCode.getAndAdd(HASH_INCREMENT);
109     }
110 
111     /**
112      * Returns the current thread's "initial value" for this
113      * thread-local variable.  This method will be invoked the first
114      * time a thread accesses the variable with the {@link #get}
115      * method, unless the thread previously invoked the {@link #set}
116      * method, in which case the {@code initialValue} method will not
117      * be invoked for the thread.  Normally, this method is invoked at
118      * most once per thread, but it may be invoked again in case of
119      * subsequent invocations of {@link #remove} followed by {@link #get}.
120      *
121      * <p>This implementation simply returns {@code null}; if the
122      * programmer desires thread-local variables to have an initial
123      * value other than {@code null}, {@code ThreadLocal} must be
124      * subclassed, and this method overridden.  Typically, an
125      * anonymous inner class will be used.
126      *
127      * @return the initial value for this thread-local

139      * @return a new thread local variable
140      * @throws NullPointerException if the specified supplier is null
141      * @since 1.8
142      */
143     public static <S> ThreadLocal<S> withInitial(Supplier<? extends S> supplier) {
144         return new SuppliedThreadLocal<>(supplier);
145     }
146 
147     /**
148      * Creates a thread local variable.
149      * @see #withInitial(java.util.function.Supplier)
150      */
151     public ThreadLocal() {
152     }
153 
154     /**
155      * Returns the value in the current thread's copy of this
156      * thread-local variable.  If the variable has no value for the
157      * current thread, it is first initialized to the value returned
158      * by an invocation of the {@link #initialValue} method.
159      * If the current thread does not support thread locals then
160      * this method returns its {@link #initialValue} (or {@code null}
161      * if the {@code initialValue} method is not overridden).
162      *
163      * @return the current thread's value of this thread-local
164      * @see Thread.Builder#allowSetThreadLocals(boolean)
165      */
166     public T get() {
167         return get(Thread.currentThread());
168     }
169 
170     /**
171      * Returns the value in the current carrier thread's copy of this
172      * thread-local variable.
173      */
174     T getCarrierThreadLocal() {
175         return get(Thread.currentCarrierThread());
176     }
177 
178     private T get(Thread t) {
179         ThreadLocalMap map = getMap(t);
180         if (map != null && map != ThreadLocalMap.NOT_SUPPORTED) {
181             ThreadLocalMap.Entry e = map.getEntry(this);
182             if (e != null) {
183                 @SuppressWarnings("unchecked")
184                 T result = (T)e.value;
185                 return result;
186             }
187         }
188         return setInitialValue(t);
189     }
190 
191     /**
192      * Returns {@code true} if there is a value in the current thread's copy of
193      * this thread-local variable, even if that values is {@code null}.
194      *
195      * @return {@code true} if current thread has associated value in this
196      *         thread-local variable; {@code false} if not
197      */
198     boolean isPresent() {
199         Thread t = Thread.currentThread();
200         ThreadLocalMap map = getMap(t);
201         if (map != null && map != ThreadLocalMap.NOT_SUPPORTED) {
202             return map.getEntry(this) != null;
203         } else {
204             return false;
205         }
206     }
207 
208     /**
209      * Variant of set() to establish initialValue. Used instead
210      * of set() in case user has overridden the set() method.
211      *
212      * @return the initial value
213      */
214     private T setInitialValue(Thread t) {
215         T value = initialValue();

216         ThreadLocalMap map = getMap(t);
217         if (map == ThreadLocalMap.NOT_SUPPORTED) {
218             return value;
219         }
220         if (map != null) {
221             map.set(this, value);
222         } else {
223             createMap(t, value);
224         }
225         if (this instanceof TerminatingThreadLocal) {
226             TerminatingThreadLocal.register((TerminatingThreadLocal<?>) this);
227         }
228         return value;
229     }
230 
231     /**
232      * Sets the current thread's copy of this thread-local variable
233      * to the specified value.  Most subclasses will have no need to
234      * override this method, relying solely on the {@link #initialValue}
235      * method to set the values of thread-locals.
236      *
237      * @param value the value to be stored in the current thread's copy of
238      *        this thread-local.
239      *
240      * @throws UnsupportedOperationException if the current thread is not
241      *         allowed to set its copy of thread-local variables
242      *
243      * @see Thread.Builder#allowSetThreadLocals(boolean)
244      */
245     public void set(T value) {
246         set(Thread.currentThread(), value);
247     }
248 
249     void setCarrierThreadLocal(T value) {
250         set(Thread.currentCarrierThread(), value);
251     }
252 
253     private void set(Thread t, T value) {
254         ThreadLocalMap map = getMap(t);
255         if (map == ThreadLocalMap.NOT_SUPPORTED) {
256             throw new UnsupportedOperationException();
257         }
258         if (map != null) {
259             map.set(this, value);
260         } else {
261             createMap(t, value);
262         }
263     }
264 
265     /**
266      * Removes the current thread's value for this thread-local
267      * variable.  If this thread-local variable is subsequently
268      * {@linkplain #get read} by the current thread, its value will be
269      * reinitialized by invoking its {@link #initialValue} method,
270      * unless its value is {@linkplain #set set} by the current thread
271      * in the interim.  This may result in multiple invocations of the
272      * {@code initialValue} method in the current thread.
273      *
274      * @since 1.5
275      */
276      public void remove() {
277          ThreadLocalMap m = getMap(Thread.currentThread());
278          if (m != null && m != ThreadLocalMap.NOT_SUPPORTED) {
279              m.remove(this);
280          }
281      }
282 
283     /**
284      * Get the map associated with a ThreadLocal. Overridden in
285      * InheritableThreadLocal.
286      *
287      * @param  t the current thread
288      * @return the map
289      */
290     ThreadLocalMap getMap(Thread t) {
291         return t.threadLocals;
292     }
293 
294     /**
295      * Create the map associated with a ThreadLocal. Overridden in
296      * InheritableThreadLocal.
297      *
298      * @param t the current thread

356     static class ThreadLocalMap {
357 
358         /**
359          * The entries in this hash map extend WeakReference, using
360          * its main ref field as the key (which is always a
361          * ThreadLocal object).  Note that null keys (i.e. entry.get()
362          * == null) mean that the key is no longer referenced, so the
363          * entry can be expunged from table.  Such entries are referred to
364          * as "stale entries" in the code that follows.
365          */
366         static class Entry extends WeakReference<ThreadLocal<?>> {
367             /** The value associated with this ThreadLocal. */
368             Object value;
369 
370             Entry(ThreadLocal<?> k, Object v) {
371                 super(k);
372                 value = v;
373             }
374         }
375 
376         static final ThreadLocalMap NOT_SUPPORTED = new ThreadLocalMap();
377 
378         /**
379          * The initial capacity -- MUST be a power of two.
380          */
381         private static final int INITIAL_CAPACITY = 16;
382 
383         /**
384          * The table, resized as necessary.
385          * table.length MUST always be a power of two.
386          */
387         private Entry[] table;
388 
389         /**
390          * The number of entries in the table.
391          */
392         private int size = 0;
393 
394         /**
395          * The next size value at which to resize.
396          */
397         private int threshold; // Default to 0

400          * Set the resize threshold to maintain at worst a 2/3 load factor.
401          */
402         private void setThreshold(int len) {
403             threshold = len * 2 / 3;
404         }
405 
406         /**
407          * Increment i modulo len.
408          */
409         private static int nextIndex(int i, int len) {
410             return ((i + 1 < len) ? i + 1 : 0);
411         }
412 
413         /**
414          * Decrement i modulo len.
415          */
416         private static int prevIndex(int i, int len) {
417             return ((i - 1 >= 0) ? i - 1 : len - 1);
418         }
419 
420         ThreadLocalMap() {
421         }
422 
423         /**
424          * Construct a new map initially containing (firstKey, firstValue).
425          * ThreadLocalMaps are constructed lazily, so we only create
426          * one when we have at least one entry to put in it.
427          */
428         ThreadLocalMap(ThreadLocal<?> firstKey, Object firstValue) {
429             table = new Entry[INITIAL_CAPACITY];
430             int i = firstKey.threadLocalHashCode & (INITIAL_CAPACITY - 1);
431             table[i] = new Entry(firstKey, firstValue);
432             size = 1;
433             setThreshold(INITIAL_CAPACITY);
434         }
435 
436         /**
437          * Construct a new map including all Inheritable ThreadLocals
438          * from given parent map. Called only by createInheritedMap.
439          *
440          * @param parentMap the map associated with parent thread.
441          */
442         private ThreadLocalMap(ThreadLocalMap parentMap) {

445             setThreshold(len);
446             table = new Entry[len];
447 
448             for (Entry e : parentTable) {
449                 if (e != null) {
450                     @SuppressWarnings("unchecked")
451                     ThreadLocal<Object> key = (ThreadLocal<Object>) e.get();
452                     if (key != null) {
453                         Object value = key.childValue(e.value);
454                         Entry c = new Entry(key, value);
455                         int h = key.threadLocalHashCode & (len - 1);
456                         while (table[h] != null)
457                             h = nextIndex(h, len);
458                         table[h] = c;
459                         size++;
460                     }
461                 }
462             }
463         }
464 
465         /**
466          * Returns the number of elements in the map.
467          */
468         int size() {
469             return size;
470         }
471 
472         /**
473          * Get the entry associated with key.  This method
474          * itself handles only the fast path: a direct hit of existing
475          * key. It otherwise relays to getEntryAfterMiss.  This is
476          * designed to maximize performance for direct hits, in part
477          * by making this method readily inlinable.
478          *
479          * @param  key the thread local object
480          * @return the entry associated with key, or null if no such
481          */
482         private Entry getEntry(ThreadLocal<?> key) {
483             int i = key.threadLocalHashCode & (table.length - 1);
484             Entry e = table[i];
485             if (e != null && e.refersTo(key))
486                 return e;
487             else
488                 return getEntryAfterMiss(key, i, e);
489         }
490 
491         /**
< prev index next >