File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Threads and Synchronization and the fly likes Thread Eats Processor Power Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Java » Threads and Synchronization
Reply Bookmark "Thread Eats Processor Power" Watch "Thread Eats Processor Power" New topic
Author

Thread Eats Processor Power

Comp Man
Greenhorn

Joined: May 01, 2005
Posts: 1
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

Joined: Jan 14, 2005
Posts: 323
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

Joined: Aug 07, 2003
Posts: 1646
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.
 
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to run our stuff on 16 servers instead of 3.
 
subject: Thread Eats Processor Power
 
Similar Threads
Another Question (.... Threads / join() )
Note on Thread
sun became private
Diff. betn multithreading and multiprocessing
Thread question