1 /*
2 * Copyright (c) 2021, 2025, 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 Thread unstarted(Runnable task, Thread preferredCarrier) {
243 Objects.requireNonNull(task);
244 var thread = newVirtualThread(scheduler,
245 preferredCarrier,
246 nextThreadName(),
247 characteristics(),
248 task);
249 UncaughtExceptionHandler uhe = uncaughtExceptionHandler();
250 if (uhe != null)
251 thread.uncaughtExceptionHandler(uhe);
252 return thread;
253 }
254
255 @Override
256 public Thread unstarted(Runnable task) {
257 return unstarted(task, null);
258 }
259
260 @Override
261 public Thread start(Runnable task) {
262 Thread thread = unstarted(task);
263 thread.start();
264 return thread;
265 }
266
267 @Override
268 public ThreadFactory factory() {
269 return new VirtualThreadFactory(scheduler, name(), counter(), characteristics(),
270 uncaughtExceptionHandler());
271 }
272
273 @SuppressWarnings("removal")
274 @CallerSensitive
275 @Override
276 public OfVirtual scheduler(Thread.VirtualThreadScheduler scheduler) {
277 if (!ContinuationSupport.isSupported()) {
278 throw new UnsupportedOperationException();
279 }
280 // can't mix custom default scheduler and API prototypes at this time
281 if (scheduler != VirtualThread.defaultScheduler()
282 && VirtualThread.defaultScheduler() != VirtualThread.builtinScheduler(true)) {
283 throw new UnsupportedOperationException();
284 }
285 Class<?> caller = Reflection.getCallerClass();
286 caller.getModule().ensureNativeAccess(OfVirtual.class, "scheduler", caller, false);
287 this.scheduler = Objects.requireNonNull(scheduler);
288 return this;
289 }
290 }
291
292 /**
293 * Base ThreadFactory implementation.
294 */
295 private abstract static class BaseThreadFactory implements ThreadFactory {
296 private static final VarHandle COUNT = MhUtil.findVarHandle(
297 MethodHandles.lookup(), "count", long.class);
298
299 private final String name;
300 private final int characteristics;
301 private final UncaughtExceptionHandler uhe;
302
303 private final boolean hasCounter;
304 private volatile long count;
305
306 BaseThreadFactory(String name,
307 long start,
308 int characteristics,
309 UncaughtExceptionHandler uhe) {
310 this.name = name;
311 if (name != null && start >= 0) {
312 this.hasCounter = true;
313 this.count = start;
314 } else {
315 this.hasCounter = false;
316 }
317 this.characteristics = characteristics;
318 this.uhe = uhe;
319 }
320
321 int characteristics() {
322 return characteristics;
323 }
324
325 UncaughtExceptionHandler uncaughtExceptionHandler() {
326 return uhe;
327 }
328
329 String nextThreadName() {
330 if (hasCounter) {
331 return name + (long) COUNT.getAndAdd(this, 1L);
332 } else {
333 return name;
334 }
335 }
336 }
337
338 /**
339 * ThreadFactory for platform threads.
340 */
341 private static class PlatformThreadFactory extends BaseThreadFactory {
342 private final ThreadGroup group;
343 private final boolean daemonChanged;
344 private final boolean daemon;
345 private final int priority;
346 private final long stackSize;
347
348 PlatformThreadFactory(ThreadGroup group,
349 String name,
350 long start,
351 int characteristics,
352 boolean daemonChanged,
353 boolean daemon,
354 int priority,
355 long stackSize,
356 UncaughtExceptionHandler uhe) {
357 super(name, start, characteristics, uhe);
358 this.group = group;
359 this.daemonChanged = daemonChanged;
360 this.daemon = daemon;
361 this.priority = priority;
362 this.stackSize = stackSize;
363 }
364
365 @Override
366 String nextThreadName() {
367 String name = super.nextThreadName();
368 return (name != null) ? name : Thread.genThreadName();
369 }
370
371 @Override
372 public Thread newThread(Runnable task) {
373 Objects.requireNonNull(task);
374 String name = nextThreadName();
375 Thread thread = new Thread(group, name, characteristics(), task, stackSize);
376 if (daemonChanged)
377 thread.daemon(daemon);
378 if (priority != 0)
379 thread.priority(priority);
380 UncaughtExceptionHandler uhe = uncaughtExceptionHandler();
381 if (uhe != null)
382 thread.uncaughtExceptionHandler(uhe);
383 return thread;
384 }
385 }
386
387 /**
388 * ThreadFactory for virtual threads.
389 */
390 private static class VirtualThreadFactory extends BaseThreadFactory {
391 private final Thread.VirtualThreadScheduler scheduler;
392
393 VirtualThreadFactory(Thread.VirtualThreadScheduler scheduler,
394 String name,
395 long start,
396 int characteristics,
397 UncaughtExceptionHandler uhe) {
398 super(name, start, characteristics, uhe);
399 this.scheduler = scheduler;
400 }
401
402 @Override
403 public Thread newThread(Runnable task) {
404 Objects.requireNonNull(task);
405 String name = nextThreadName();
406 Thread thread = newVirtualThread(scheduler, null, name, characteristics(), task);
407 UncaughtExceptionHandler uhe = uncaughtExceptionHandler();
408 if (uhe != null)
409 thread.uncaughtExceptionHandler(uhe);
410 return thread;
411 }
412 }
413
414 /**
415 * Creates a new virtual thread to run the given task.
416 */
417 private static Thread newVirtualThread(Thread.VirtualThreadScheduler scheduler,
418 Thread preferredCarrier,
419 String name,
420 int characteristics,
421 Runnable task) {
422 if (ContinuationSupport.isSupported()) {
423 return new VirtualThread(scheduler, preferredCarrier, name, characteristics, task);
424 } else {
425 if (scheduler != null)
426 throw new UnsupportedOperationException();
427 return new BoundVirtualThread(name, characteristics, task);
428 }
429 }
430
431 static Thread newVirtualThread(String name, int characteristics, Runnable task) {
432 return newVirtualThread(null, null, name, characteristics, task);
433 }
434
435 /**
436 * A "virtual thread" that is backed by a platform thread. This implementation
437 * is intended for platforms that don't have the underlying VM support for
438 * continuations. It can also be used for testing.
439 */
440 static final class BoundVirtualThread extends BaseVirtualThread {
441 private static final Unsafe U = Unsafe.getUnsafe();
442 private final Runnable task;
443 private boolean runInvoked;
444
445 BoundVirtualThread(String name, int characteristics, Runnable task) {
446 super(name, characteristics, true);
447 this.task = task;
448 }
449
450 @Override
451 public void run() {
452 // run is specified to do nothing when Thread is a virtual thread
453 if (Thread.currentThread() == this && !runInvoked) {
454 runInvoked = true;
455 Object bindings = Thread.scopedValueBindings();
456 runWith(bindings, task);
457 }
458 }
459
460 @Override
461 void park() {
462 U.park(false, 0L);
463 }
464
465 @Override
466 void parkNanos(long nanos) {
467 U.park(false, nanos);
468 }
469
470 @Override
471 void unpark() {
472 U.unpark(this);
473 }
474
475 @Override
476 public String toString() {
477 StringBuilder sb = new StringBuilder("VirtualThread[#");
478 sb.append(threadId());
479 String name = getName();
480 if (!name.isEmpty()) {
481 sb.append(",");
482 sb.append(name);
483 }
484 sb.append("]/");
485 String stateAsString = threadState().toString();
486 sb.append(stateAsString.toLowerCase(Locale.ROOT));
487 return sb.toString();
488 }
489 }
490 }