Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why not to use thread.sleep for no reason, and explain it to a programmer

Tags:

c#

asp.net

While passing through code in our project I came across a web method that had this code at the end of it:

thread.sleep(6000);
return true;

Now, this was done so the jQuery ajax call from the client gets delayed and the ajax animation will show for a little bit longer.

This is very wrong in my eyes. There shouldn't be this kind of connection between UI and server side. If he wants the animation to take longer he can use the setTimeOut function in the client side.

Here is my problem: how can I explain to the programmer why this is so wrong? Not just because the client/server thing, but why ever call thread.sleep on a website?

like image 604
guy schaller Avatar asked Nov 10 '10 13:11

guy schaller


People also ask

Why should we not use thread sleep?

Thread. sleep is bad! It blocks the current thread and renders it unusable for further work.

When should you use thread sleep?

Use it whenever you need a long pause in your operations. If the spec says 'now wait at least 10 seconds before continuing', then call sleep(10000).

Is thread sleep a good practice?

Using Thread. sleep() frequently in an automation framework is not a good practice. If the applied sleep is of 5 secs and the web element is displayed in 2 secs only, the extra 3 secs will increase the execution time. And if you use it more often in the framework, the execution time would increase drastically.

What is the alternative for thread sleep?

Alternative: use wait() and notify() Now we have to refactor our test as well. After we start the counter we need to block the thread running the test until the counting is over. Remember, the counting happens in a different thread.


1 Answers

While delaying:

  • You are using/blocking a thread
  • You are consuming memory
  • You have an open TCP/IP connection

these are all expensive resources on server

Because:

  • If another requests comes in, the odds are greater a new thread must be created, so this will use CPU, memory etc, and this will delay this request. (Goto start of sentence).
  • More memory consumption, means more page faults, larger disk queue. All requests take longer.
  • TCP/IP connections are a limited resource.
like image 144
GvS Avatar answered Sep 21 '22 11:09

GvS