KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > java > lang > InheritableThreadLocal


1 /*
2  * @(#)InheritableThreadLocal.java 1.21 04/02/09
3  *
4  * Copyright 2004 Sun Microsystems, Inc. All rights reserved.
5  * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
6  */

7
8 package java.lang;
9 import java.lang.ref.*;
10
11 /**
12  * This class extends <tt>ThreadLocal</tt> to provide inheritance of values
13  * from parent thread to child thread: when a child thread is created, the
14  * child receives initial values for all inheritable thread-local variables
15  * for which the parent has values. Normally the child's values will be
16  * identical to the parent's; however, the child's value can be made an
17  * arbitrary function of the parent's by overriding the <tt>childValue</tt>
18  * method in this class.
19  *
20  * <p>Inheritable thread-local variables are used in preference to
21  * ordinary thread-local variables when the per-thread-attribute being
22  * maintained in the variable (e.g., User ID, Transaction ID) must be
23  * automatically transmitted to any child threads that are created.
24  *
25  * @author Josh Bloch and Doug Lea
26  * @version 1.21, 02/09/04
27  * @see ThreadLocal
28  * @since 1.2
29  */

30
31 public class InheritableThreadLocal<T> extends ThreadLocal JavaDoc<T> {
32     /**
33      * Computes the child's initial value for this inheritable thread-local
34      * variable as a function of the parent's value at the time the child
35      * thread is created. This method is called from within the parent
36      * thread before the child is started.
37      * <p>
38      * This method merely returns its input argument, and should be overridden
39      * if a different behavior is desired.
40      *
41      * @param parentValue the parent thread's value
42      * @return the child thread's initial value
43      */

44     protected T childValue(T parentValue) {
45         return parentValue;
46     }
47
48     /**
49      * Get the map associated with a ThreadLocal.
50      *
51      * @param t the current thread
52      */

53     ThreadLocalMap getMap(Thread JavaDoc t) {
54        return t.inheritableThreadLocals;
55     }
56
57     /**
58      * Create the map associated with a ThreadLocal.
59      *
60      * @param t the current thread
61      * @param firstValue value for the initial entry of the table.
62      * @param map the map to store.
63      */

64     void createMap(Thread JavaDoc t, T firstValue) {
65         t.inheritableThreadLocals = new ThreadLocalMap(this, firstValue);
66     }
67 }
68
Popular Tags