Java Concurrency Interview

Threads and lifecycle question 9 of 180 mid

Does Thread.yield() do anything you can rely on?

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.

scheduling

Quiz yourself on Threads and lifecycle Suggest a correction