ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ForkJoinWorkerThread.java
Revision: 1.60
Committed: Tue May 6 17:31:01 2014 UTC (10 years ago) by dl
Branch: MAIN
Changes since 1.59: +137 -11 lines
Log Message:
Sync with openjdk

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     * requires that we break quite a lot of encapulation (via Unsafe)
41     * 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.58 return workQueue.poolIndex >>> 1; // ignore odd/even tag bit
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     * Erases ThreadLocals by nulling out Thread maps
146     */
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    
174     } catch (Exception e) {
175     throw new Error(e);
176     }
177     }
178    
179     /**
180     * A worker thread that has no permissions, is not a member of any
181     * user-defined ThreadGroup, and erases all ThreadLocals after
182     * running each top-level task.
183     */
184     static final class InnocuousForkJoinWorkerThread extends ForkJoinWorkerThread {
185     /** The ThreadGroup for all InnocuousForkJoinWorkerThreads */
186     private static final ThreadGroup innocuousThreadGroup =
187     createThreadGroup();
188    
189     /** An AccessControlContext supporting no privileges */
190     private static final AccessControlContext INNOCUOUS_ACC =
191     new AccessControlContext(
192     new ProtectionDomain[] {
193     new ProtectionDomain(null, null)
194     });
195    
196     InnocuousForkJoinWorkerThread(ForkJoinPool pool) {
197     super(pool, innocuousThreadGroup, INNOCUOUS_ACC);
198     }
199    
200     @Override // to erase ThreadLocals
201     void afterTopLevelExec() {
202     eraseThreadLocals();
203     }
204    
205     @Override // to always report system loader
206     public ClassLoader getContextClassLoader() {
207     return ClassLoader.getSystemClassLoader();
208     }
209    
210     @Override // to silently fail
211     public void setUncaughtExceptionHandler(UncaughtExceptionHandler x) { }
212    
213     @Override // paranoically
214     public void setContextClassLoader(ClassLoader cl) {
215     throw new SecurityException("setContextClassLoader");
216     }
217    
218     /**
219     * Returns a new group with the system ThreadGroup (the
220     * topmost, parentless group) as parent. Uses Unsafe to
221     * traverse Thread group and ThreadGroup parent fields.
222     */
223     private static ThreadGroup createThreadGroup() {
224     try {
225     sun.misc.Unsafe u = sun.misc.Unsafe.getUnsafe();
226     Class<?> tk = Thread.class;
227     Class<?> gk = ThreadGroup.class;
228     long tg = u.objectFieldOffset(tk.getDeclaredField("group"));
229     long gp = u.objectFieldOffset(gk.getDeclaredField("parent"));
230     ThreadGroup group = (ThreadGroup)
231     u.getObject(Thread.currentThread(), tg);
232     while (group != null) {
233     ThreadGroup parent = (ThreadGroup)u.getObject(group, gp);
234     if (parent == null)
235     return new ThreadGroup(group,
236     "InnocuousForkJoinWorkerThreadGroup");
237     group = parent;
238     }
239     } catch (Exception e) {
240     throw new Error(e);
241 dl 1.45 }
242 dl 1.60 // fall through if null as cannot-happen safeguard
243     throw new Error("Cannot create ThreadGroup");
244 dl 1.45 }
245 jsr166 1.1 }
246 dl 1.60
247 jsr166 1.1 }
248 dl 1.60