Friday, April 26, 2019

Why Thread.Sleep is bad Practice


  1. The thread time slice varies from OS to OS and processor to processor. This means that once your thread goes to sleep, it’s going to wait for its turn to come back into the scheduler. So it’s highly likely that the thread.sleep time means more than what you really intended. For example, with thread.sleep(1000), you intended 1,000 milliseconds, but it could potentially sleep for more than 1,000 milliseconds too as it waits for its turn in the scheduler.
  1. Each thread has its own use of CPU and virtual memory. That means our thread acquired its resources (say 1MB virtual memory, some CPU cycles and some context switching cycles), and is simply not using them.
  1. If it’s a foreground thread, it’s preventing the application from exiting as well.
  1. What about Thread.Sleep(0)? This tells the processor that I’m ready to lose the remainder of my time slice, and you may pick up the next thread from the queue. On one hand, it feels good and efficient. But on the other hand, you are also telling the processor that you are better at scheduling than the processor. (I don’t know the side effects this can cause, but I’m not smarter than the processor.)
We are talking about milliseconds when dealing with thread.sleep, but it’s important to understand that the more we use thread.sleep, the more we defer solving the real problem, which is how to handle async in modern web apps.

No comments:

Post a Comment