…the post title is a bit harsh – but true in most cases.
Too often Thread.sleep is used to make the main application thread pause when it needs to wait for resources to be initialized on a secondary thread, like so:
while (resourceNotInitialized){
Thread.sleep (someArbitraryNumberOfMilliSeconds);
}
While this solution has the advantage of being easy to understand, it also has one drawback: it’s wrong.
Or more precisely the number of milliseconds the main thread must sleep for is most likely wrong:
- either it’s too small and the main thread will repeatedly awake too early, hogging CPU resources in the process (buzy wait)
- or it’s too large and the main thread will wake up long after all resources have been initialized, resulting in an application with sluggish behaviour (and irate users).
The proper way to handle this scenario is to use the wait and notify methods from the Object class.
- Decide on an instance (or class) on which both the main thread and secondary thread can synchronize
- Main thread starts the secondary thread and acquires the monitor (enters synchronized block)
- Main thread then waits, effectively releasing the monitor
- When the secondary thread is done it acquires in turn the monitor and notifies the main thread.
- Main thread wakes up and resumes it course
A bit more convoluted than Thread.sleep, granted, but much nicer and more importantly, bug-proof and latency-resistant
