Skip to content

Commit 5f34c1b

Browse files
committed
fix: Remove Thread.yield()
1 parent 0ca8f6f commit 5f34c1b

File tree

2 files changed

+10
-2
lines changed

2 files changed

+10
-2
lines changed

src/dev/enola/be/task/Task.java

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,14 @@ protected Task(I input) {
2727
/**
2828
* The main logic of the task.
2929
*
30+
* <p>This method is called by the {@link TaskExecutor} when the task is executed. It will run
31+
* in a virtual thread of modern Java. For long-running tasks, please ensure to periodically
32+
* check for interruption via {@link Thread#isInterrupted()} and terminate early if so, by
33+
* throwing {@link InterruptedException}. Please do not, under any circumstances, use the
34+
* ancient {@link Thread#yield()} method within implementations of this method (or anywhere
35+
* really anymore, nowadays); as it will cause performance degradation by a factor of x100 for
36+
* no benefit at all anymore on modern Java, especially on virtual threads.
37+
*
3038
* @return output, never null (use {@link Empty#INSTANCE}; or {@link Optional}, if needed)
3139
* @throws Exception in case of any failure
3240
*/

src/dev/enola/be/task/demo/LongIncrementingTask.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ public LongIncrementingTask(Input input, CheckedConsumer<Long, IOException> prog
3030
protected Output execute() throws Exception {
3131
for (long i = 0; i < input.max; i++) {
3232
progressConsumer.accept(i);
33-
Thread.yield();
33+
// Do *NOT* Thread.yield(); that makes it really horribly slow, by like a factor x100!
3434
if (Thread.currentThread().isInterrupted())
3535
throw new InterruptedException("Task was interrupted");
3636
Threads.sleep(input.sleep);
@@ -44,7 +44,7 @@ protected Output execute() throws Exception {
4444
private static void simpleLoop(long max, Duration sleep) throws InterruptedException {
4545
var start = Instant.now();
4646
for (long i = 0; i < max; i++) {
47-
// Thread.yield();
47+
// Do *NOT* Thread.yield(); that makes it really horribly slow, by like a factor x100!
4848
Threads.sleep(sleep);
4949
}
5050
var duration = Duration.between(start, Instant.now());

0 commit comments

Comments
 (0)