This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
I have written a client that connects to a server on a tcp socket and waits for bytes to come in. The class implements Runnable. In the Run portion of the code I have a while loop and check to see if there are any available bytes in the DataInputStream and process them if they are present.
Problem is I have to do a "Thread.sleep(30)" in the loop or else the program hangs. With this sleep code in place, my program works fine in Windows but not in Linux. However if I increase the sleep time to 100 mSec then it works in Linux also. This just doesn't make sense. I think, although the code works with having a sleep in place, it might not be the way correct Java should be written for a client who is waiting for bytes.
So what is it thet I am doing wrong and how to code correctly for listening bytes coming in?
You definitely should not have the sleep. Just read in a loop. The read call will block until there's data available. Usually this will be done in its own thread, so other parts of the app aren't blocked waiting for the read, and if it's a GUI app, you definitely should not do it in the GUI thread, otherwise you'll stop your GUI from responding to user actions and updating itself.