Win a copy of Murach's Python Programming this week in the Jython/Python forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Thread Eats Processor Power  RSS feed

 
Comp Man
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hey everyone. I'm new to Java, so I thought a cool way to learn would be to write a chat client. I'm happy to report that it's going pretty good, except for one major problem.

When I'm ready for the program to connect, it'll start up a thread for handling socket communications. The thread will start by sending the initial handshake and enter a loop for incoming messages. The problem is that it starts consuming processor avalibility, so that nothing else will work until I exit the program. How do I prevent this from happening?

Thanks!
 
M Beck
Ranch Hand
Posts: 323
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
how are you reading these messages from the other end? in most cases, a network client/server program will use a read() or readLine() or readObject() method on some stream or Reader object, and these methods will block quietly until there's input to be had. why aren't yours blocking?
 
David Harkness
Ranch Hand
Posts: 1646
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can you post the code that performs the reading? That would increase help us to help you.

I do have a guess, though. Are you calling available() on the Socket's InputStream inside a loop until it returns a value greater than zero? This would cause the thread to greedily eat up CPU cycles until some data arrived.

Replace the loop and available() call with a call to one of the read() methods. If there is no data available, the thread will sleep (no CPU time taken) until data arrives. At that point the JVM wakes the thread so it can continue with the read() call.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!