1 /*
2 * Copyright (c) 2021, 2024, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
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 package java.lang;
26
27 import java.lang.Thread.Builder.OfPlatform;
28 import java.lang.Thread.Builder.OfVirtual;
29 import java.lang.Thread.UncaughtExceptionHandler;
30 import java.lang.invoke.MethodHandles;
31 import java.lang.invoke.VarHandle;
32 import java.util.Locale;
33 import java.util.Objects;
34 import java.util.concurrent.ThreadFactory;
35 import jdk.internal.misc.Unsafe;
36 import jdk.internal.invoke.MhUtil;
37 import jdk.internal.reflect.CallerSensitive;
38 import jdk.internal.reflect.Reflection;
39 import jdk.internal.vm.ContinuationSupport;
40
41 /**
42 * Defines static methods to create platform and virtual thread builders.
43 */
44 class ThreadBuilders {
45 private ThreadBuilders() { }
46
47 /**
48 * Base class for Thread.Builder implementations.
49 */
50 private static class BaseThreadBuilder {
51 private String name;
52 private long counter;
53 private int characteristics;
54 private UncaughtExceptionHandler uhe;
55
56 String name() {
57 return name;
58 }
59
60 long counter() {
61 return counter;
62 }
63
64 int characteristics() {
65 return characteristics;
66 }
67
68 UncaughtExceptionHandler uncaughtExceptionHandler() {
69 return uhe;
70 }
71
72 String nextThreadName() {
73 if (name != null && counter >= 0) {
74 return name + (counter++);
75 } else {
76 return name;
77 }
78 }
79
80 void setName(String name) {
81 this.name = Objects.requireNonNull(name);
82 this.counter = -1;
83 }
84
85 void setName(String prefix, long start) {
86 Objects.requireNonNull(prefix);
87 if (start < 0)
88 throw new IllegalArgumentException("'start' is negative");
89 this.name = prefix;
90 this.counter = start;
91 }
92
93 void setInheritInheritableThreadLocals(boolean inherit) {
94 if (inherit) {
95 characteristics &= ~Thread.NO_INHERIT_THREAD_LOCALS;
96 } else {
97 characteristics |= Thread.NO_INHERIT_THREAD_LOCALS;
98 }
99 }
100
101 void setUncaughtExceptionHandler(UncaughtExceptionHandler ueh) {
102 this.uhe = Objects.requireNonNull(ueh);
103 }
104 }
105
106 /**
107 * ThreadBuilder.OfPlatform implementation.
108 */
109 static final class PlatformThreadBuilder
110 extends BaseThreadBuilder implements OfPlatform {
111 private ThreadGroup group;
112 private boolean daemon;
113 private boolean daemonChanged;
114 private int priority;
115 private long stackSize;
116
117 PlatformThreadBuilder() {
118 }
119
120 @Override
121 String nextThreadName() {
122 String name = super.nextThreadName();
123 return (name != null) ? name : Thread.genThreadName();
124 }
125
126 @Override
127 public OfPlatform name(String name) {
128 setName(name);
129 return this;
130 }
131
132 @Override
133 public OfPlatform name(String prefix, long start) {
134 setName(prefix, start);
135 return this;
136 }
137
138 @Override
139 public OfPlatform inheritInheritableThreadLocals(boolean inherit) {
140 setInheritInheritableThreadLocals(inherit);
141 return this;
142 }
143
144 @Override
145 public OfPlatform uncaughtExceptionHandler(UncaughtExceptionHandler ueh) {
146 setUncaughtExceptionHandler(ueh);
147 return this;
148 }
149
150 @Override
151 public OfPlatform group(ThreadGroup group) {
152 this.group = Objects.requireNonNull(group);
153 return this;
154 }
155
156 @Override
157 public OfPlatform daemon(boolean on) {
158 daemon = on;
159 daemonChanged = true;
160 return this;
161 }
162
163 @Override
164 public OfPlatform priority(int priority) {
165 if (priority < Thread.MIN_PRIORITY || priority > Thread.MAX_PRIORITY)
166 throw new IllegalArgumentException();
167 this.priority = priority;
168 return this;
169 }
170
171 @Override
172 public OfPlatform stackSize(long stackSize) {
173 if (stackSize < 0L)
174 throw new IllegalArgumentException();
175 this.stackSize = stackSize;
176 return this;
177 }
178
179 @Override
180 public Thread unstarted(Runnable task) {
181 Objects.requireNonNull(task);
182 String name = nextThreadName();
183 var thread = new Thread(group, name, characteristics(), task, stackSize);
184 if (daemonChanged)
185 thread.daemon(daemon);
186 if (priority != 0)
187 thread.priority(priority);
188 UncaughtExceptionHandler uhe = uncaughtExceptionHandler();
189 if (uhe != null)
190 thread.uncaughtExceptionHandler(uhe);
191 return thread;
192 }
193
194 @Override
195 public Thread start(Runnable task) {
196 Thread thread = unstarted(task);
197 thread.start();
198 return thread;
199 }
200
201 @Override
202 public ThreadFactory factory() {
203 return new PlatformThreadFactory(group, name(), counter(), characteristics(),
204 daemonChanged, daemon, priority, stackSize, uncaughtExceptionHandler());
205 }
206 }
207
208 /**
209 * ThreadBuilder.OfVirtual implementation.
210 */
211 static final class VirtualThreadBuilder
212 extends BaseThreadBuilder implements OfVirtual {
213 private Thread.VirtualThreadScheduler scheduler;
214
215 VirtualThreadBuilder() {
216 }
217
218 @Override
219 public OfVirtual name(String name) {
220 setName(name);
221 return this;
222 }
223
224 @Override
225 public OfVirtual name(String prefix, long start) {
226 setName(prefix, start);
227 return this;
228 }
229
230 @Override
231 public OfVirtual inheritInheritableThreadLocals(boolean inherit) {
232 setInheritInheritableThreadLocals(inherit);
233 return this;
234 }
235
236 @Override
237 public OfVirtual uncaughtExceptionHandler(UncaughtExceptionHandler ueh) {
238 setUncaughtExceptionHandler(ueh);
239 return this;
240 }
241
242 @Override
243 public Thread unstarted(Runnable task) {
244 Objects.requireNonNull(task);
245 var thread = newVirtualThread(scheduler,
246 null,
247 nextThreadName(),
248 characteristics(),
249 task,
250 null);
251 UncaughtExceptionHandler uhe = uncaughtExceptionHandler();
252 if (uhe != null)
253 thread.uncaughtExceptionHandler(uhe);
254 return thread;
255 }
256
257 @Override
258 public Thread start(Runnable task) {
259 Thread thread = unstarted(task);
260 thread.start();
261 return thread;
262 }
263
264 @Override
265 public ThreadFactory factory() {
266 return new VirtualThreadFactory(scheduler, name(), counter(), characteristics(),
267 uncaughtExceptionHandler());
268 }
269
270 @CallerSensitive
271 @Override
272 public Thread unstarted(Runnable task, Thread preferredCarrier, Object att) {
273 Objects.requireNonNull(task);
274 Class<?> caller = Reflection.getCallerClass();
275 caller.getModule().ensureNativeAccess(OfVirtual.class, "unstarted", caller, false);
276 var thread = newVirtualThread(scheduler,
277 preferredCarrier,
278 nextThreadName(),
279 characteristics(),
280 task,
281 att);
282 UncaughtExceptionHandler uhe = uncaughtExceptionHandler();
283 if (uhe != null)
284 thread.uncaughtExceptionHandler(uhe);
285 return thread;
286 }
287
288 @CallerSensitive
289 @Override
290 public OfVirtual scheduler(Thread.VirtualThreadScheduler scheduler) {
291 if (!ContinuationSupport.isSupported()) {
292 throw new UnsupportedOperationException();
293 }
294 // can't mix custom default scheduler and API prototypes at this time
295 if (scheduler != VirtualThread.defaultScheduler()
296 && VirtualThread.defaultScheduler() != VirtualThread.builtinScheduler()) {
297 throw new UnsupportedOperationException();
298 }
299 Class<?> caller = Reflection.getCallerClass();
300 caller.getModule().ensureNativeAccess(OfVirtual.class, "scheduler", caller, false);
301 this.scheduler = Objects.requireNonNull(scheduler);
302 return this;
303 }
304 }
305
306 /**
307 * Base ThreadFactory implementation.
308 */
309 private abstract static class BaseThreadFactory implements ThreadFactory {
310 private static final VarHandle COUNT = MhUtil.findVarHandle(
311 MethodHandles.lookup(), "count", long.class);
312
313 private final String name;
314 private final int characteristics;
315 private final UncaughtExceptionHandler uhe;
316
317 private final boolean hasCounter;
318 private volatile long count;
319
320 BaseThreadFactory(String name,
321 long start,
322 int characteristics,
323 UncaughtExceptionHandler uhe) {
324 this.name = name;
325 if (name != null && start >= 0) {
326 this.hasCounter = true;
327 this.count = start;
328 } else {
329 this.hasCounter = false;
330 }
331 this.characteristics = characteristics;
332 this.uhe = uhe;
333 }
334
335 int characteristics() {
336 return characteristics;
337 }
338
339 UncaughtExceptionHandler uncaughtExceptionHandler() {
340 return uhe;
341 }
342
343 String nextThreadName() {
344 if (hasCounter) {
345 return name + (long) COUNT.getAndAdd(this, 1L);
346 } else {
347 return name;
348 }
349 }
350 }
351
352 /**
353 * ThreadFactory for platform threads.
354 */
355 private static class PlatformThreadFactory extends BaseThreadFactory {
356 private final ThreadGroup group;
357 private final boolean daemonChanged;
358 private final boolean daemon;
359 private final int priority;
360 private final long stackSize;
361
362 PlatformThreadFactory(ThreadGroup group,
363 String name,
364 long start,
365 int characteristics,
366 boolean daemonChanged,
367 boolean daemon,
368 int priority,
369 long stackSize,
370 UncaughtExceptionHandler uhe) {
371 super(name, start, characteristics, uhe);
372 this.group = group;
373 this.daemonChanged = daemonChanged;
374 this.daemon = daemon;
375 this.priority = priority;
376 this.stackSize = stackSize;
377 }
378
379 @Override
380 String nextThreadName() {
381 String name = super.nextThreadName();
382 return (name != null) ? name : Thread.genThreadName();
383 }
384
385 @Override
386 public Thread newThread(Runnable task) {
387 Objects.requireNonNull(task);
388 String name = nextThreadName();
389 Thread thread = new Thread(group, name, characteristics(), task, stackSize);
390 if (daemonChanged)
391 thread.daemon(daemon);
392 if (priority != 0)
393 thread.priority(priority);
394 UncaughtExceptionHandler uhe = uncaughtExceptionHandler();
395 if (uhe != null)
396 thread.uncaughtExceptionHandler(uhe);
397 return thread;
398 }
399 }
400
401 /**
402 * ThreadFactory for virtual threads.
403 */
404 private static class VirtualThreadFactory extends BaseThreadFactory {
405 private final Thread.VirtualThreadScheduler scheduler;
406
407 VirtualThreadFactory(Thread.VirtualThreadScheduler scheduler,
408 String name,
409 long start,
410 int characteristics,
411 UncaughtExceptionHandler uhe) {
412 super(name, start, characteristics, uhe);
413 this.scheduler = scheduler;
414 }
415
416 @Override
417 public Thread newThread(Runnable task) {
418 Objects.requireNonNull(task);
419 String name = nextThreadName();
420 Thread thread = newVirtualThread(scheduler, null, name, characteristics(), task, null);
421 UncaughtExceptionHandler uhe = uncaughtExceptionHandler();
422 if (uhe != null)
423 thread.uncaughtExceptionHandler(uhe);
424 return thread;
425 }
426 }
427
428 /**
429 * Creates a new virtual thread to run the given task.
430 */
431 private static Thread newVirtualThread(Thread.VirtualThreadScheduler scheduler,
432 Thread preferredCarrier,
433 String name,
434 int characteristics,
435 Runnable task,
436 Object att) {
437 if (ContinuationSupport.isSupported()) {
438 return new VirtualThread(scheduler, preferredCarrier, name, characteristics, task, att);
439 } else {
440 if (scheduler != null)
441 throw new UnsupportedOperationException();
442 return new BoundVirtualThread(name, characteristics, task);
443 }
444 }
445
446 static Thread newVirtualThread(String name, int characteristics, Runnable task) {
447 return newVirtualThread(null, null, name, characteristics, task, null);
448 }
449
450 /**
451 * A "virtual thread" that is backed by a platform thread. This implementation
452 * is intended for platforms that don't have the underlying VM support for
453 * continuations. It can also be used for testing.
454 */
455 static final class BoundVirtualThread extends BaseVirtualThread {
456 private static final Unsafe U = Unsafe.getUnsafe();
457 private final Runnable task;
458 private boolean runInvoked;
459
460 BoundVirtualThread(String name, int characteristics, Runnable task) {
461 super(name, characteristics, true);
462 this.task = task;
463 }
464
465 @Override
466 public void run() {
467 // run is specified to do nothing when Thread is a virtual thread
468 if (Thread.currentThread() == this && !runInvoked) {
469 runInvoked = true;
470 Object bindings = Thread.scopedValueBindings();
471 runWith(bindings, task);
472 }
473 }
474
475 @Override
476 void park() {
477 U.park(false, 0L);
478 }
479
480 @Override
481 void parkNanos(long nanos) {
482 U.park(false, nanos);
483 }
484
485 @Override
486 void unpark() {
487 U.unpark(this);
488 }
489
490 @Override
491 public String toString() {
492 StringBuilder sb = new StringBuilder("VirtualThread[#");
493 sb.append(threadId());
494 String name = getName();
495 if (!name.isEmpty()) {
496 sb.append(",");
497 sb.append(name);
498 }
499 sb.append("]/");
500 String stateAsString = threadState().toString();
501 sb.append(stateAsString.toLowerCase(Locale.ROOT));
502 return sb.toString();
503 }
504 }
505 }