1 /* 2 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 3 * 4 * This code is free software; you can redistribute it and/or modify it 5 * under the terms of the GNU General Public License version 2 only, as 6 * published by the Free Software Foundation. Oracle designates this 7 * particular file as subject to the "Classpath" exception as provided 8 * by Oracle in the LICENSE file that accompanied this code. 9 * 10 * This code is distributed in the hope that it will be useful, but WITHOUT 11 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 12 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 13 * version 2 for more details (a copy is included in the LICENSE file that 14 * accompanied this code). 15 * 16 * You should have received a copy of the GNU General Public License version 17 * 2 along with this work; if not, write to the Free Software Foundation, 18 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 19 * 20 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 21 * or visit www.oracle.com if you need additional information or have any 22 * questions. 23 */ 24 25 /* 26 * This file is available under and governed by the GNU General Public 27 * License version 2 only, as published by the Free Software Foundation. 28 * However, the following notice accompanied the original version of this 29 * file: 30 * 31 * Written by Doug Lea with assistance from members of JCP JSR-166 32 * Expert Group and released to the public domain, as explained at 33 * http://creativecommons.org/publicdomain/zero/1.0/ 34 */ 35 36 package java.util.concurrent; 37 38 import java.security.AccessControlContext; 39 import java.security.AccessController; 40 import java.security.PrivilegedAction; 41 import java.security.ProtectionDomain; 42 43 /** 44 * A thread managed by a {@link ForkJoinPool}, which executes 45 * {@link ForkJoinTask}s. 46 * This class is subclassable solely for the sake of adding 47 * functionality -- there are no overridable methods dealing with 48 * scheduling or execution. However, you can override initialization 49 * and termination methods surrounding the main task processing loop. 50 * If you do create such a subclass, you will also need to supply a 51 * custom {@link ForkJoinPool.ForkJoinWorkerThreadFactory} to 52 * {@linkplain ForkJoinPool#ForkJoinPool(int, ForkJoinWorkerThreadFactory, 53 * UncaughtExceptionHandler, boolean, int, int, int, Predicate, long, TimeUnit) 54 * use it} in a {@code ForkJoinPool}. 55 * 56 * @since 1.7 57 * @author Doug Lea 58 */ 59 public class ForkJoinWorkerThread extends Thread { 60 /* 61 * ForkJoinWorkerThreads are managed by ForkJoinPools and perform 62 * ForkJoinTasks. For explanation, see the internal documentation 63 * of class ForkJoinPool. 64 * 65 * This class just maintains links to its pool and WorkQueue. The 66 * pool field is set immediately upon construction, but the 67 * workQueue field is not set until a call to registerWorker 68 * completes. This leads to a visibility race, that is tolerated 69 * by requiring that the workQueue field is only accessed by the 70 * owning thread. 71 * 72 * Support for (non-public) subclass InnocuousForkJoinWorkerThread 73 * requires that we break quite a lot of encapsulation (via helper 74 * methods in ThreadLocalRandom) both here and in the subclass to 75 * access and set Thread fields. 76 */ 77 78 final ForkJoinPool pool; // the pool this thread works in 79 final ForkJoinPool.WorkQueue workQueue; // work-stealing mechanics 80 81 /** 82 * Creates a ForkJoinWorkerThread operating in the given pool. 83 * 84 * @param pool the pool this thread works in 85 * @throws NullPointerException if pool is null 86 */ 87 protected ForkJoinWorkerThread(ForkJoinPool pool) { 88 // Use a placeholder until a useful name can be set in registerWorker 89 super("aForkJoinWorkerThread"); 90 this.pool = pool; 91 this.workQueue = pool.registerWorker(this); 92 } 93 94 /** 95 * Version for use by the default pool. Supports setting the 96 * context class loader. This is a separate constructor to avoid 97 * affecting the protected constructor. 98 */ 99 ForkJoinWorkerThread(ForkJoinPool pool, ClassLoader ccl) { 100 super("aForkJoinWorkerThread"); 101 super.setContextClassLoader(ccl); 102 this.pool = pool; 103 this.workQueue = pool.registerWorker(this); 104 } 105 106 /** 107 * Version for InnocuousForkJoinWorkerThread. 108 */ 109 ForkJoinWorkerThread(ForkJoinPool pool, 110 ClassLoader ccl, 111 ThreadGroup threadGroup, 112 AccessControlContext acc) { 113 super(threadGroup, null, "aForkJoinWorkerThread"); 114 super.setContextClassLoader(ccl); 115 ThreadLocalRandom.setInheritedAccessControlContext(this, acc); 116 ThreadLocalRandom.eraseThreadLocals(this); // clear before registering 117 this.pool = pool; 118 this.workQueue = pool.registerWorker(this); 119 } 120 121 /** 122 * Returns the pool hosting this thread. 123 * 124 * @return the pool 125 */ 126 public ForkJoinPool getPool() { 127 return pool; 128 } 129 130 /** 131 * Returns the unique index number of this thread in its pool. 132 * The returned value ranges from zero to the maximum number of 133 * threads (minus one) that may exist in the pool, and does not 134 * change during the lifetime of the thread. This method may be 135 * useful for applications that track status or collect results 136 * per-worker-thread rather than per-task. 137 * 138 * @return the index number 139 */ 140 public int getPoolIndex() { 141 return workQueue.getPoolIndex(); 142 } 143 144 /** 145 * Initializes internal state after construction but before 146 * processing any tasks. If you override this method, you must 147 * invoke {@code super.onStart()} at the beginning of the method. 148 * Initialization requires care: Most fields must have legal 149 * default values, to ensure that attempted accesses from other 150 * threads work correctly even before this thread starts 151 * processing tasks. 152 */ 153 protected void onStart() { 154 } 155 156 /** 157 * Performs cleanup associated with termination of this worker 158 * thread. If you override this method, you must invoke 159 * {@code super.onTermination} at the end of the overridden method. 160 * 161 * @param exception the exception causing this thread to abort due 162 * to an unrecoverable error, or {@code null} if completed normally 163 */ 164 protected void onTermination(Throwable exception) { 165 } 166 167 /** 168 * This method is required to be public, but should never be 169 * called explicitly. It performs the main run loop to execute 170 * {@link ForkJoinTask}s. 171 */ 172 public void run() { 173 if (workQueue.array == null) { // only run once 174 Throwable exception = null; 175 try { 176 onStart(); 177 pool.runWorker(workQueue); 178 } catch (Throwable ex) { 179 exception = ex; 180 } finally { 181 try { 182 onTermination(exception); 183 } catch (Throwable ex) { 184 if (exception == null) 185 exception = ex; 186 } finally { 187 pool.deregisterWorker(this, exception); 188 } 189 } 190 } 191 } 192 193 /** 194 * Non-public hook method for InnocuousForkJoinWorkerThread. 195 */ 196 void afterTopLevelExec() { 197 } 198 199 /** 200 * A worker thread that has no permissions, is not a member of any 201 * user-defined ThreadGroup, uses the system class loader as 202 * thread context class loader, and erases all ThreadLocals after 203 * running each top-level task. 204 */ 205 static final class InnocuousForkJoinWorkerThread extends ForkJoinWorkerThread { 206 /** The ThreadGroup for all InnocuousForkJoinWorkerThreads */ 207 private static final ThreadGroup innocuousThreadGroup = 208 AccessController.doPrivileged(new PrivilegedAction<>() { 209 public ThreadGroup run() { 210 ThreadGroup group = Thread.currentThread().getThreadGroup(); 211 for (ThreadGroup p; (p = group.getParent()) != null; ) 212 group = p; 213 return new ThreadGroup( 214 group, "InnocuousForkJoinWorkerThreadGroup"); 215 }}); 216 217 /** An AccessControlContext supporting no privileges */ 218 private static final AccessControlContext INNOCUOUS_ACC = 219 new AccessControlContext( 220 new ProtectionDomain[] { new ProtectionDomain(null, null) }); 221 222 InnocuousForkJoinWorkerThread(ForkJoinPool pool) { 223 super(pool, 224 ClassLoader.getSystemClassLoader(), 225 innocuousThreadGroup, 226 INNOCUOUS_ACC); 227 } 228 229 @Override // to erase ThreadLocals 230 void afterTopLevelExec() { 231 ThreadLocalRandom.eraseThreadLocals(this); 232 } 233 234 @Override // to silently fail 235 public void setUncaughtExceptionHandler(UncaughtExceptionHandler x) { } 236 237 @Override // paranoically 238 public void setContextClassLoader(ClassLoader cl) { 239 throw new SecurityException("setContextClassLoader"); 240 } 241 } 242 }