Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is thread sleep necessary when reading from a socket stream?

I am reading from a socket input stream like this

BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String line;

while((line = in.readLine()) != null){
   // do something
   Thread.sleep(10); // for example 10ms
}

Now, the read method of an input stream blocks until data is available.

In this case is cooling-down the thread a good idea? After 10ms it will be blocking anyway.

Please do not tell me about non-blocking IO, I know about that.

I am just curious whether it helps performance/CPU in anyway.

like image 370
Marc Avatar asked Dec 21 '22 00:12

Marc


2 Answers

No. There's no reason to sleep. Why artificially slow down the read loop? Let it read data as fast as it comes in.

like image 183
John Kugelman Avatar answered Dec 25 '22 23:12

John Kugelman


If you want to let other threads a cpu time, you should use:

Thread.yield();

But I'm not think it's necessary here- let the system thread scheduling do its job- it's pretty good.

like image 29
shem Avatar answered Dec 26 '22 00:12

shem