Too often Thread.sleep is used to make the main application thread pause when it needs to wait for resources to be initialised on a secondary thread, like so:
While this solution has the advantage of being easy to understand, it also has one drawback: 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 initialised, resulting in an application with sluggish behaviour (and irate users).
The proper way to handle this scenario is to coordinate both threads either by using the wait and notify methods from the Object class, or alternatively with a countdownLatch.