Quiz: Thread.yield() in Java: What It Does and When to Use It
Study the lesson first: Thread.yield() in Java: What It Does and When to Use It
Total: 5 questions
1. What does Thread.yield() do in Java?
What does Thread.yield() do in Java?
Thread.yield() is a static method of the Thread class that hints to the scheduler that the current thread is willing to give up the CPU. The scheduler is free to ignore the hint; the Javadoc says plainly that it is rarely appropriate to use this method.
- the thread stays in the
RUNNABLEstate: it doesn't sleep and may continue right away; - monitors it holds (
synchronized) are not released; - the method throws no checked exceptions, takes no parameters and can't hand control to a specific thread;
- the method is static: calling
other.yield()makes the current thread yield, notother.
For a platform thread, HotSpot hands the call over to the OS (sched_yield() on Linux, SwitchToThread() on Windows), so the result depends on the platform and the number of free cores.
2. How does Thread.yield() differ from Thread.sleep() and Object.wait()?
How does Thread.yield() differ from Thread.sleep() and Object.wait()?
- State: after
yield()the thread staysRUNNABLE;sleep()moves it toTIMED_WAITING,wait()toWAITINGorTIMED_WAITING. - Pause:
yield()has none and may not give up the CPU at all;sleep()is guaranteed to take the thread off the CPU for the given time,wait()waits fornotify()/notifyAll()or a timeout. - Monitor:
yield()andsleep()keep it,wait()releases it while waiting. - Exceptions:
yield()throws no checked exceptions;sleep()andwait()throwInterruptedException.
The closest call to yield() is Thread.sleep(0): in practice it is also a hint with no real pause, but it throws InterruptedException if the interrupt flag is already set, while yield() doesn't check that flag.
3. When should you use Thread.yield(), and what should replace it in a busy-wait loop?
When should you use Thread.yield(), and what should replace it in a busy-wait loop?
Application code almost never needs yield(). The documentation names two scenarios:
- tests and debugging - a
yield()between reading and writing a shared variable widens the window for a thread switch, so a race condition shows up on almost every run (it is then fixed with synchronization or atomic classes); - low-level primitives with a short busy wait - for example,
ConcurrentHashMap.initTable().
For a spin-wait loop, Java 9 added Thread.onSpinWait() (JEP 285): it hints not to the OS but to the CPU (the PAUSE instruction on x86). yield() itself returns immediately when cores are free and doesn't reduce the load. For ordinary waiting for an event, take the thread off scheduling: wait()/notify(), CountDownLatch, LockSupport.park().
4. How does Thread.yield() work in virtual threads (Java 21)?
How does Thread.yield() work in virtual threads (Java 21)?
In a virtual thread, 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 runs another virtual thread.
This is where the method has a noticeable effect: by default there are as many carriers as cores, while virtual threads can number in the thousands. A long computation without blocking calls occupies a carrier completely, and a periodic yield() gives the others a chance. The carrier can't be released if the thread is pinned to it: while running a native method, and in Java 21-23 also inside a synchronized block.
5. What is the difference between Thread.yield() and the yield keyword in switch?
What is the difference between Thread.yield() and the yield keyword in switch?
They are unrelated: Thread.yield() is a method of the Thread class for working with threads, while yield in Java 14+ is a language statement that returns a value from a { } block inside a switch expression:
String type = switch (day) {
case 6, 7 -> {
String result = "weekend";
yield result;
}
default -> "weekday";
};
They meet in exactly one place: since Java 14 yield is a restricted identifier, and the line yield(); inside a Thread subclass, which compiled in Java 8, fails with invalid use of a restricted identifier 'yield'. So always call the method with the class name: Thread.yield().