Threads and lifecycle question 9 of 180 mid
Does Thread.yield() do anything you can rely on?
- Yes, it guarantees another thread runs next
- Correct: No, it is a hint to the scheduler with no guarantees, useful mainly in spin loops via
onSpinWait - It releases every lock the thread holds
- It puts the thread into WAITING
yield() suggests to the scheduler that the current thread is willing to give up its slice. The
scheduler may immediately reschedule the same thread, and the specification requires nothing. Code
whose correctness depends on yield() is broken code that happens to pass on one machine.
It also does not release locks, which is what separates it from Object.wait(). If a spin loop is
genuinely what you want, Thread.onSpinWait() (Java 9) is the right tool: it emits a PAUSE
instruction and tells the CPU that this is a spin, without involving the scheduler at all.