views:

515

answers:

4

If I call read() on a DataInputStream, will it take up CPU cycles waiting for data or does it yield the current thread and get woken up by an interrupt signaling that data has arrived?

My motivation for asking the question is to determine whether or not a stream reader needs to be in its own thread or not. A blocking read that takes up CPU time would not be ideal as this would hang the main thread.

Related question: When a method is described as a blocking, does it IMPLY that the thread yields while waiting? Or is there no contract/guarantee? A method that constantly checks/polls for data still blocks, it sounds, to me.

Please let me know.

+1  A: 

It does not take up CPU cycles, but, being blocking, nothing else gets executed either.

If you can, use Java's NIO, which is non-blocking. Otherwise, having a separate thread might be ideal.

Daniel
+3  A: 

Generally, I/O will cause the reading thread to block until data is available, and other threads are free to run. When data arrives, the reader is unblocked.

Blocking implies that the blocked thread waits to be unblocked, while other threads run. You don't generally find (in well designed code - and not in the Java runtime) busy-waiting code which loops while polling for data.

On the other hand, I've seen just about everything in code which I've had to take over :-(

Vinay Sajip
+1  A: 

There is a certain amount of cycles that are taken up by blocking. There is the thread switch. Associated problems with having caches full of unhelpful data. Possibly, on multithreaded machines, there is a short period of spinning in case the thread can be unblocked quickly without the context switch.

So, there's a tiny bit of overhead. However, once that is out of the way it should not be a problem. The fact that you are using DataInputStream is neither here nor there. If you see any specific performance problems, address those. I/O performance is likely to be more important than CPU performance for I/O operations.

Tom Hawtin - tackline
A: 

You're fine from a threading point of view (as per the other answers) -- no/minimal CPU use in blocking.

HOWEVER, don't expect high I/O performance -- because the InputStream read methods are synchronized, blocking, and perform safety checks for EVERY byte they are quite slow. If you're reading bulk data, look into NIO or read a large byte[] at a time. 1K-8K is more or less standard.

BobMcGee