Thread.sleep: avoid

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 (resourceNotInitialized){
Thread.sleep (someArbitraryNumberOfMilliSeconds);

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.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s