ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ForkJoinWorkerThread.java
Revision: 1.66
Committed: Sun Jan 4 01:06:15 2015 UTC (9 years, 5 months ago) by jsr166
Branch: MAIN
Changes since 1.65: +2 -3 lines
Log Message:
use ReflectiveOperationException for Unsafe mechanics

File Contents

# User Rev Content
1 jsr166 1.1 /*
2     * Written by Doug Lea with assistance from members of JCP JSR-166
3     * Expert Group and released to the public domain, as explained at
4 jsr166 1.46 * http://creativecommons.org/publicdomain/zero/1.0/
5 jsr166 1.1 */
6    
7     package java.util.concurrent;
8    
9 dl 1.60 import java.security.AccessControlContext;
10     import java.security.ProtectionDomain;
11    
12 jsr166 1.1 /**
13 jsr166 1.40 * A thread managed by a {@link ForkJoinPool}, which executes
14     * {@link ForkJoinTask}s.
15     * This class is subclassable solely for the sake of adding
16     * functionality -- there are no overridable methods dealing with
17     * scheduling or execution. However, you can override initialization
18     * and termination methods surrounding the main task processing loop.
19     * If you do create such a subclass, you will also need to supply a
20 jsr166 1.57 * custom {@link ForkJoinPool.ForkJoinWorkerThreadFactory} to
21     * {@linkplain ForkJoinPool#ForkJoinPool use it} in a {@code ForkJoinPool}.
22 jsr166 1.1 *
23     * @since 1.7
24     * @author Doug Lea
25     */
26     public class ForkJoinWorkerThread extends Thread {
27     /*
28 dl 1.14 * ForkJoinWorkerThreads are managed by ForkJoinPools and perform
29 dl 1.52 * ForkJoinTasks. For explanation, see the internal documentation
30     * of class ForkJoinPool.
31 dl 1.55 *
32     * This class just maintains links to its pool and WorkQueue. The
33 dl 1.56 * pool field is set immediately upon construction, but the
34     * workQueue field is not set until a call to registerWorker
35     * completes. This leads to a visibility race, that is tolerated
36     * by requiring that the workQueue field is only accessed by the
37     * owning thread.
38 dl 1.60 *
39     * Support for (non-public) subclass InnocuousForkJoinWorkerThread
40 jsr166 1.62 * requires that we break quite a lot of encapsulation (via Unsafe)
41 dl 1.60 * both here and in the subclass to access and set Thread fields.
42 jsr166 1.1 */
43    
44 dl 1.52 final ForkJoinPool pool; // the pool this thread works in
45 dl 1.56 final ForkJoinPool.WorkQueue workQueue; // work-stealing mechanics
46 dl 1.54
47     /**
48 jsr166 1.1 * Creates a ForkJoinWorkerThread operating in the given pool.
49     *
50     * @param pool the pool this thread works in
51     * @throws NullPointerException if pool is null
52     */
53     protected ForkJoinWorkerThread(ForkJoinPool pool) {
54 dl 1.56 // Use a placeholder until a useful name can be set in registerWorker
55     super("aForkJoinWorkerThread");
56 dl 1.55 this.pool = pool;
57 dl 1.56 this.workQueue = pool.registerWorker(this);
58 dl 1.14 }
59    
60 jsr166 1.1 /**
61 dl 1.60 * Version for InnocuousForkJoinWorkerThread
62     */
63     ForkJoinWorkerThread(ForkJoinPool pool, ThreadGroup threadGroup,
64     AccessControlContext acc) {
65     super(threadGroup, null, "aForkJoinWorkerThread");
66     U.putOrderedObject(this, INHERITEDACCESSCONTROLCONTEXT, acc);
67     eraseThreadLocals(); // clear before registering
68     this.pool = pool;
69     this.workQueue = pool.registerWorker(this);
70     }
71    
72     /**
73 jsr166 1.1 * Returns the pool hosting this thread.
74     *
75     * @return the pool
76     */
77     public ForkJoinPool getPool() {
78     return pool;
79     }
80    
81     /**
82 jsr166 1.59 * Returns the unique index number of this thread in its pool.
83     * The returned value ranges from zero to the maximum number of
84     * threads (minus one) that may exist in the pool, and does not
85     * change during the lifetime of the thread. This method may be
86     * useful for applications that track status or collect results
87     * per-worker-thread rather than per-task.
88 jsr166 1.1 *
89     * @return the index number
90     */
91     public int getPoolIndex() {
92 dl 1.65 return workQueue.getPoolIndex();
93 dl 1.45 }
94    
95 jsr166 1.1 /**
96 dl 1.14 * Initializes internal state after construction but before
97     * processing any tasks. If you override this method, you must
98 jsr166 1.39 * invoke {@code super.onStart()} at the beginning of the method.
99 dl 1.14 * Initialization requires care: Most fields must have legal
100     * default values, to ensure that attempted accesses from other
101     * threads work correctly even before this thread starts
102     * processing tasks.
103 jsr166 1.1 */
104 dl 1.14 protected void onStart() {
105     }
106 jsr166 1.1
107     /**
108 dl 1.14 * Performs cleanup associated with termination of this worker
109     * thread. If you override this method, you must invoke
110     * {@code super.onTermination} at the end of the overridden method.
111 jsr166 1.4 *
112 dl 1.14 * @param exception the exception causing this thread to abort due
113     * to an unrecoverable error, or {@code null} if completed normally
114 jsr166 1.1 */
115 dl 1.14 protected void onTermination(Throwable exception) {
116 jsr166 1.1 }
117    
118     /**
119     * This method is required to be public, but should never be
120     * called explicitly. It performs the main run loop to execute
121 jsr166 1.40 * {@link ForkJoinTask}s.
122 jsr166 1.1 */
123     public void run() {
124 dl 1.60 if (workQueue.array == null) { // only run once
125     Throwable exception = null;
126 dl 1.52 try {
127 dl 1.60 onStart();
128     pool.runWorker(workQueue);
129 dl 1.52 } catch (Throwable ex) {
130 dl 1.60 exception = ex;
131 dl 1.52 } finally {
132 dl 1.60 try {
133     onTermination(exception);
134     } catch (Throwable ex) {
135     if (exception == null)
136     exception = ex;
137     } finally {
138     pool.deregisterWorker(this, exception);
139     }
140     }
141     }
142     }
143    
144     /**
145 jsr166 1.63 * Erases ThreadLocals by nulling out Thread maps.
146 dl 1.60 */
147     final void eraseThreadLocals() {
148     U.putObject(this, THREADLOCALS, null);
149     U.putObject(this, INHERITABLETHREADLOCALS, null);
150     }
151    
152     /**
153     * Non-public hook method for InnocuousForkJoinWorkerThread
154     */
155     void afterTopLevelExec() {
156     }
157    
158     // Set up to allow setting thread fields in constructor
159     private static final sun.misc.Unsafe U;
160     private static final long THREADLOCALS;
161     private static final long INHERITABLETHREADLOCALS;
162     private static final long INHERITEDACCESSCONTROLCONTEXT;
163     static {
164     try {
165     U = sun.misc.Unsafe.getUnsafe();
166     Class<?> tk = Thread.class;
167     THREADLOCALS = U.objectFieldOffset
168     (tk.getDeclaredField("threadLocals"));
169     INHERITABLETHREADLOCALS = U.objectFieldOffset
170     (tk.getDeclaredField("inheritableThreadLocals"));
171     INHERITEDACCESSCONTROLCONTEXT = U.objectFieldOffset
172     (tk.getDeclaredField("inheritedAccessControlContext"));
173 jsr166 1.66 } catch (ReflectiveOperationException e) {
174 dl 1.60 throw new Error(e);
175     }
176     }
177    
178     /**
179     * A worker thread that has no permissions, is not a member of any
180     * user-defined ThreadGroup, and erases all ThreadLocals after
181     * running each top-level task.
182     */
183     static final class InnocuousForkJoinWorkerThread extends ForkJoinWorkerThread {
184     /** The ThreadGroup for all InnocuousForkJoinWorkerThreads */
185     private static final ThreadGroup innocuousThreadGroup =
186     createThreadGroup();
187    
188     /** An AccessControlContext supporting no privileges */
189     private static final AccessControlContext INNOCUOUS_ACC =
190     new AccessControlContext(
191     new ProtectionDomain[] {
192     new ProtectionDomain(null, null)
193     });
194    
195     InnocuousForkJoinWorkerThread(ForkJoinPool pool) {
196     super(pool, innocuousThreadGroup, INNOCUOUS_ACC);
197     }
198    
199     @Override // to erase ThreadLocals
200     void afterTopLevelExec() {
201     eraseThreadLocals();
202     }
203    
204     @Override // to always report system loader
205     public ClassLoader getContextClassLoader() {
206     return ClassLoader.getSystemClassLoader();
207     }
208    
209     @Override // to silently fail
210     public void setUncaughtExceptionHandler(UncaughtExceptionHandler x) { }
211    
212     @Override // paranoically
213     public void setContextClassLoader(ClassLoader cl) {
214     throw new SecurityException("setContextClassLoader");
215     }
216    
217     /**
218     * Returns a new group with the system ThreadGroup (the
219 jsr166 1.62 * topmost, parent-less group) as parent. Uses Unsafe to
220 jsr166 1.64 * traverse Thread.group and ThreadGroup.parent fields.
221 dl 1.60 */
222     private static ThreadGroup createThreadGroup() {
223     try {
224     sun.misc.Unsafe u = sun.misc.Unsafe.getUnsafe();
225     Class<?> tk = Thread.class;
226     Class<?> gk = ThreadGroup.class;
227     long tg = u.objectFieldOffset(tk.getDeclaredField("group"));
228     long gp = u.objectFieldOffset(gk.getDeclaredField("parent"));
229     ThreadGroup group = (ThreadGroup)
230     u.getObject(Thread.currentThread(), tg);
231     while (group != null) {
232     ThreadGroup parent = (ThreadGroup)u.getObject(group, gp);
233     if (parent == null)
234     return new ThreadGroup(group,
235     "InnocuousForkJoinWorkerThreadGroup");
236     group = parent;
237     }
238 jsr166 1.66 } catch (ReflectiveOperationException e) {
239 dl 1.60 throw new Error(e);
240 dl 1.45 }
241 dl 1.60 // fall through if null as cannot-happen safeguard
242     throw new Error("Cannot create ThreadGroup");
243 dl 1.45 }
244 jsr166 1.1 }
245 dl 1.60
246 jsr166 1.1 }