I'm reading a Java book I found a sentence that seems incorrect:
When reading, if there's no data available, the thread will be blocked until it new data will be available. Notice that this is a typical asynchronous behavior, the threads are communicating through a channel(pipe).
Why does the author call the operation "asynchronous"? Shouldn't asynchronous imply that the thread will NOT be blocked until it receives new data?
Later Edit:
I run this code and it from the output it seems the behaviour is asynchronous.
Here is a part of the output: http://ideone.com/qijn0B
And the code is below. What do you think?
import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author dragos
*/
class Consumator extends Thread{
DataInputStream in;
public Consumator(DataInputStream in){
this.in = in;
}
public void run(){
int value = -1;
for(int i=0;i<=1000;i++){
try {
value = in.readInt();
} catch (IOException ex) {
Logger.getLogger(Consumator.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println("Consumator received: "+ value);
}
}
}
class Producator extends Thread{
DataOutputStream out;
public Producator(DataOutputStream out){
this.out = out;
}
public void run(){
for(int i=0;i<=1000;i++){
try {
out.writeInt(i);
} catch (IOException ex) {
Logger.getLogger(Producator.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println("Producator wrote: "+i);
}
}
}
public class TestPipes {
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws IOException {
PipedInputStream pipeIn = new PipedInputStream();
PipedOutputStream pipeOut = new PipedOutputStream(pipeIn);
DataInputStream in = new DataInputStream(pipeIn);
DataOutputStream out = new DataOutputStream(pipeOut);
Consumator c = new Consumator(in);
Producator p = new Producator(out);
p.start();
c.start();
}
}
Why does the author call the operation "asynchronous"? Shouldn't asynchronous imply that the thread will NOT be blocked until it receives new data?
Either this is incorrect or the author is talking about how the consumer thread would block but the producer thread would still run. At the very least this wording is certainly confusing.
In any case, the PipeInputStream
and PipeOutputStream
streams share an internal buffer but otherwise are "synchronous". If the buffer is full the writer will block and if the buffer is empty the reader will block.