Socket InputStream blocks on available() / read()
It is not blocking it is spinning.
Once there is no data available you code might as well read
while (true)
{
if (buffIn.available() > 0) // ALWAYS false now we've run out of data
{
// unreachable
}
}
The loop will never finish. Your test for the minus 1 value will never be executed when there is no data available.
You are seeing available() in the stack trace because that's about the only thing in your loop that's taking up any time, so the chances are, when you create you stack trace, that's where it's going to be.
If you are confident that you will infact get an end-of-file condition (eg if it's TCP and the other end closes the connection) then the available() call is not required at all. Otherwise, you need a different method of determining you have all of the data. For example is the payload size encoded in the first few bytes or something?
when does FileInputStream.read() block?
The answer to your question can be found in the JavaDoc for .read():
This method blocks if no input is yet available.
and
Returns: the next byte of data, or -1 if the end of the file is reached.
So, an empty file will get you an immediate -1
(instead of read()
blocking) as
- there is input available, since the file exists
- ...but it is empty, so immediate EOF.
The ...No input is yet available... situation could occur eg. when one was to read from a named pipe instead of a plain file, and the other side of the pipe hasn't written anything yet.
Cheers,
Why does reading from Process' InputStream block altough data is available
Why does reading from Process' InputStream block although data is available
It doesn't. The problem here is that data isn't available when you think it is, and that's caused by buffering at the sender.
You can overcome that with fflush()
as per @MarkkuK.'s comment, or by telling stdio
not to buffer stdout
at all, as per yours.
Related Topics
Change Location of Log4J.Properties
Generics:List<? Extends Animal> Is Same as List<Animal>
Populate Jtable with Large Number of Rows
Calling a @Bean Annotated Method in Spring Java Configuration
Deserialize JSON to Arraylist<Pojo> Using Jackson
How Many Threads Are Spawned in Parallelstream in Java 8
Adding an Http Header to the Request in a Servlet Filter
General Strategy to Resolve Java Memory Leak
Java, How to Implement a Shift Cipher (Caesar Cipher)
Why Can't You Have Multiple Interfaces in a Bounded Wildcard Generic
How to Convert a Java Object (Bean) to Key-Value Pairs (And Vice Versa)
Java: Convert String to Timestamp