Threads ·
‹ Previous Next ›
⏱ 5 min read Modified: 2026-11-22

Thread.yield() in Java: What It Does and When to Use It

Thread.yield() is a static method that returns the running thread to the runnable state so that another thread can take its place. More precisely, it is a hint to the scheduler: "the current thread is willing to give up the CPU". The scheduler is free to ignore it, the thread stays in the RUNNABLE state and may continue right away, and any monitors it holds (synchronized) are not released.

Thread.yield(); // give up the CPU if the scheduler sees fit

Old Java 8 tutorials often called the method without the class name, which is legal inside a subclass of Thread. Since Java 14 the line yield(); no longer compiles: yield became a keyword of switch expressions, and javac reports invalid use of a restricted identifier 'yield'. If you were actually looking for the yield keyword in switch, jump to Thread.yield() vs the yield keyword in switch.

Thread.yield() Signature and What the Javadoc Promises

Thread.yield() is a static method of java.lang.Thread with no parameters and no return value, and it throws no checked exceptions. In Java 8–18 it is declared as public static native void yield(). Starting with Java 19 it is a regular Java method: for a platform thread it calls a native method, for a virtual thread it gives up the carrier thread.

// Java 8–18
public static native void yield();

// Java 19+ (simplified, based on the JDK sources)
public static void yield() {
    if (currentThread() instanceof VirtualThread vthread) {
        vthread.tryYield();   // the virtual thread gives up its carrier
    } else {
        yield0();             // native: an OS system call
    }
}

For a platform thread, HotSpot hands the call over to the operating system: sched_yield() on Linux, SwitchToThread() on Windows. What the OS does next is outside Java's control.

The Javadoc describes the method very cautiously: "A hint to the scheduler that the current thread is willing to yield its current use of a processor. The scheduler is free to ignore this hint". And then, quite bluntly: "It is rarely appropriate to use this method". The documentation names two scenarios where it can help: debugging and testing, to reproduce race conditions, and building low-level concurrency primitives like the ones in java.util.concurrent.locks. Both are covered in When Thread.yield() is actually useful.

Thread.yield() Example: Two Threads

Two threads run the same task: each prints its name and step number and calls Thread.yield() after every step. You might expect a neat A, B, A, B sequence, but yield() doesn't guarantee it, and the output changes from run to run.

public class YieldExample {
    public static void main(String[] args) {
        Runnable task = () -> {
            for (int i = 1; i <= 3; i++) {
                System.out.println(Thread.currentThread().getName() + ": " + i);
                Thread.yield();
            }
        };

        new Thread(task, "A").start();
        new Thread(task, "B").start();
    }
}

One possible output:

A: 1
A: 2
A: 3
B: 1
B: 2
B: 3

Another run on the same machine:

A: 1
B: 1
A: 2
B: 2
B: 3
A: 3

Here's why. On a multi-core CPU, threads A and B usually run at the same time on different cores, so there is nobody to yield to: sched_yield() returns immediately. On top of that, thread A often prints everything before B has even started, because creating a thread takes longer than three println() calls. The order of lines is decided by the OS scheduler and the number of free cores, not by the yield() calls. Code whose correctness depends on interleaving must not rely on yield().

What Happens to a Thread When It Calls yield()

After Thread.yield() the thread stays RUNNABLE: it doesn't sleep, doesn't wait for an event and doesn't release the monitors it holds. If the scheduler takes the hint, the thread simply joins the queue of threads ready to run and may get the CPU back a moment later.

The Thread.State enum has no separate "running" state: a thread that is executing and a thread waiting for a CPU are both RUNNABLE. So getState() returns the same value before and after yield().

Priorities. Older SCJP certification guides state a rule like "yield() only gives way to threads of the same or higher priority". Neither the Javadoc nor the JLS promises that: how the OS treats Java thread priorities depends on the platform. Code that relies on priorities tends to end up with threads that rarely get the CPU at all — see deadlock vs livelock vs starvation.

Data visibility. The Java Language Specification (JLS §17.9) says explicitly that neither Thread.sleep() nor Thread.yield() has any synchronization semantics. The compiler doesn't have to flush cached values to memory before the call or reload them afterwards.

What does this code print?

public class YieldVisibility {
    static boolean done = false; // not volatile

    public static void main(String[] args) throws InterruptedException {
        Thread waiter = new Thread(() -> {
            while (!done) {
                Thread.yield();
            }
            System.out.println("Saw done = true");
        });
        waiter.start();

        Thread.sleep(100);
        done = true;
        waiter.join();
    }
}
Saw done = true

On HotSpot the program usually finishes: the native call inside the loop prevents the JIT compiler from caching the done field. But that's an implementation detail. Under the JLS, the waiter thread is allowed to never see true and spin forever, and yield() doesn't fix that. The correct fix is to declare the field volatile, which guarantees that a write in one thread becomes visible to others, or to guard it with synchronization.

A yield that gives nothing away

Thread.yield() inside a synchronized block doesn't help threads waiting for the same monitor: the monitor stays with the current thread, and they remain BLOCKED. If another thread needs to enter the critical section, build the waiting on wait(), which releases the monitor. sleep() and join() keep the monitor just like yield() — the same problem with sleep() is shown in the Thread.sleep() lesson.

When Thread.yield() Is Actually Useful

In application code Thread.yield() is almost never used. It helps in the two cases the documentation itself names: in tests, to reproduce race conditions more often, and inside low-level busy-waiting constructs (spin-wait). For the second case, Java 9 added a better-suited method, Thread.onSpinWait().

Reproducing a race. A race condition can stay hidden on a developer's machine for years. Put a yield() between reading and writing a shared variable, and the window for a thread switch gets wider, so the bug shows up on almost every run:

public class RaceWithYield {
    static int counter = 0;

    public static void main(String[] args) throws InterruptedException {
        Runnable increment = () -> {
            for (int i = 0; i < 1000; i++) {
                int tmp = counter;
                Thread.yield();     // widen the window between read and write
                counter = tmp + 1;
            }
        };

        Thread a = new Thread(increment);
        Thread b = new Thread(increment);
        a.start();
        b.start();
        a.join();
        b.join();

        System.out.println("counter = " + counter);
    }
}

Output: counter = followed by a number that is almost always less than 2000 and changes from run to run. Some increments are lost: both threads read the same value and wrote the same result. This doesn't fix anything; it makes the problem visible, and the fix is synchronization (synchronized) or atomic classes such as AtomicInteger. join() here makes main wait until both threads finish.

Busy-waiting in library code. The JDK does use yield() internally: for example, ConcurrentHashMap calls it in initTable() when another thread is already initializing the table and the wait should be short. A brief wait in a loop is cheaper than putting a thread to sleep and waking it up later. But yield() in such a loop has a downside: if no other threads are ready to run, the call returns immediately, and the loop keeps a core at 100%.

For busy-wait loops, Java 9 introduced Thread.onSpinWait() (JEP 285). It doesn't go to the OS scheduler; instead it tells the CPU that a spin-wait is in progress. On x86 the JIT turns the call into the PAUSE instruction, which lowers power consumption and doesn't get in the way of the second hardware thread on the same core.

// ready is declared volatile
while (!ready) {
    Thread.onSpinWait();
}
How to wait What happens When it fits
Empty loop while (!ready) {} The core is fully busy; other threads on it suffer Practically never
Thread.onSpinWait() (Java 9+) A hint to the CPU; the thread doesn't give up the core Very short waits in low-level code
Thread.yield() A hint to the OS scheduler; returns immediately if cores are free Waits that may drag on when there are more ready threads than cores
wait()/notify(), CountDownLatch, LockSupport.park() The thread is taken off scheduling until a signal arrives; no CPU is used Ordinary waiting for an event in application code

If you're writing a regular application rather than your own lock implementation, the last row of the table is your option.

yield() vs sleep() vs wait()

All three methods let other threads run in one way or another, but they work differently. yield() is only a hint, and the thread stays RUNNABLE. sleep() is guaranteed to take the thread off the CPU for the given time. wait() waits for a signal and is the only one of the three that releases the monitor.

Aspect Thread.yield() Thread.sleep() Object.wait()
Thread state RUNNABLE TIMED_WAITING WAITING or TIMED_WAITING
Pause None; may not give up the CPU at all At least the given time Until notify()/notifyAll() or a timeout
Monitor Kept Kept Released while waiting
Exceptions No checked exceptions InterruptedException InterruptedException; outside synchronized — IllegalMonitorStateException
Declared in Static method of Thread Static method of Thread Instance method of Object

Pausing for a set time, InterruptedException, sleep(0) and a detailed sleep-vs-wait comparison are covered in the lesson Thread.sleep() in Java.

Thread.yield() in Virtual Threads (Java 21)

In a virtual thread (Java 21+), Thread.yield() doesn't call the OS. The virtual thread is unmounted from its carrier thread and put back into the virtual-thread scheduler's queue, while the carrier picks up another virtual thread.

This is where the method has a noticeable effect. By default there are as many platform carrier threads as cores, while virtual threads can number in the thousands. A long computation without blocking calls occupies a carrier completely, and a yield() inside such a loop gives the other virtual threads a chance. The carrier can't be released if the virtual thread is pinned to it: for example, while running a native method, and in Java 21–23 also while inside a synchronized block (Java 24 removed that case).

Thread vt = Thread.ofVirtual().start(() -> {
    long sum = 0;
    for (int i = 0; i < 1_000_000; i++) {
        sum += i;
        if (i % 100_000 == 0) {
            Thread.yield(); // free the carrier for other virtual threads
        }
    }
    System.out.println("sum = " + sum);
});
vt.join();
// Output: sum = 499999500000

Thread.yield() vs the yield Keyword in switch

The Java yield keyword (Java 14+) has nothing to do with threads: it returns a value from a { } block inside a switch expression. People searching for "yield in Java" may mean either one, but Thread.yield() is a method of the Thread class, while yield in switch is a language statement.

int day = 6;
String type = switch (day) {
    case 1, 2, 3, 4, 5 -> "weekday";
    case 6, 7 -> {
        String result = "weekend";
        yield result;             // the value of the whole switch expression
    }
    default -> throw new IllegalArgumentException("day: " + day);
};
System.out.println(type);
// Output: weekend

Switch expression syntax, arrow labels and when you can do without yield are covered in the lesson The switch statement in Java.

The two meet in exactly one place. Since Java 14, yield is a restricted identifier, and calling a method with that name without a qualifier is not allowed. Inside a subclass of Thread, the line yield(); that compiled in Java 8 now fails with invalid use of a restricted identifier 'yield'. The fix is to always write Thread.yield(). You can still declare a variable named yield, but it's better not to.

Frequently Asked Questions

What is the difference between Thread.yield() and Thread.sleep(0)?

In practice both calls are a hint to the scheduler with no real pause, and their behavior depends on the JVM and OS. The formal differences: sleep(0) is declared with throws InterruptedException and throws it if the interrupt flag is already set, while yield() throws no checked exceptions and doesn't check the interrupt flag.

Can yield() hand control to a specific thread?

No. The method takes no parameters and knows nothing about other threads: which thread gets the CPU, if any, is up to the scheduler. If one thread has to wait for another, use join(), wait()/notify() or the synchronizers from java.util.concurrent — see the table in When Thread.yield() is actually useful.

Does yield() in a waiting loop reduce CPU usage?

Only when there are more ready threads than cores. If cores are free, yield() returns immediately, and a loop like while (!ready) Thread.yield(); loads the core almost as much as an empty one. To stop a thread from using the CPU, take it off scheduling: wait(), LockSupport.park(), CountDownLatch.await().

What happens if you call yield() through a reference to another thread?

The call other.yield() compiles (the IDE warns about a static method accessed via an instance), but it's the current thread that yields, not other. The method is static and always applies to the thread that executes it. There is no way to make another thread yield from the outside.

Comments

Please log in or register to have a possibility to add comment.