Thursday 7 February 2013

Thread.yield() vs Thread.sleep(0)

1. First major difference is sleep can throw interrupted exception where yield doesn't.
2. Its implementation varies in different JVM implementation. In windows till Java 5 Yield use to call sleep(0) internally but from Java 6 implementation has changed.


Note:
Using Thread.yield() is not an effective strategy as you are increasing OS level calls and making the OS context scheduler do more work - in the worst case this can mean a system gets swamped doing context switching.
There are JVM options to control how yield works, e.g. -XX:+DontYieldALot makes yields get ignored.