Thread.yield

This static method is essentially used to notify the system that the current thread is willing to "give up the CPU" for a while. The general idea is that:

The thread scheduler will select a different thread to run instead of the current one.

However, the details of how yielding is implemented by the thread scheduler differ from platform to platform. In general, you shouldn't rely on it behaving in a particular way. Things that differ include:

Windows

In the Hotspot implementation, the way that Thread.yield() works has changed between Java 5 and Java 6.

In Java 5, Thread.yield() calls the Windows API call Sleep(0). This has the special effect of clearing the current thread's quantum and putting it to the end of the queue for its priority level. In other words, all runnable threads of the same priority (and those of greater priority) will get a chance to run before the yielded thread is next given CPU time. When it is eventually re-scheduled, it will come back with a full full quantum, but doesn't "carry over" any of the remaining quantum from the time of yielding. This behaviour is a little different from a non-zero sleep where the sleeping thread generally loses 1 quantum value (in effect, 1/3 of a 10 or 15ms tick).

In Java 6, this behaviour was changed. The Hotspot VM now implements Thread.yield() using the Windows SwitchToThread() API call. This call makes the current thread give up its current timeslice, but not its entire quantum. This means that depending on the priorities of other threads, the yielding thread can be scheduled back in one interrupt period later. (See the section on thread scheduling for more information on timeslices.)

Linux

Under Linux, Hotspot simply calls sched_yield(). The consequences of this call are a little different, and possibly more severe than under Windows:

(See the section on thread scheduling for more details on priorities and scheduling algorithms.)

When to use yield()?

I would say practically never. Its behaviour isn't standardly defined and there are generally better ways to perform the tasks that you might want to perform with yield():


If you enjoy this Java programming article, please share with friends and colleagues. Follow the author on Twitter for the latest news and rants.

Editorial page content written by Neil Coffey. Copyright © Javamex UK 2021. All rights reserved.