Reputation: 367
I am making a java application that uses piped input/output streams (with a Object input/output stream wrapper around them). I was getting a pretty big delay when sending data over and thought it was because of my data's size initially. However the following demonstration shows the native delay in piped input/output streams when communicating on different threads.
public class Main{
public static long millis = 0;
public static void main(String[] args) throws Exception {
JFrame frame = new JFrame();
JButton button = new JButton("Press me");
frame.getContentPane().add(button);
frame.setSize(new Dimension(500, 500));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
PipedInputStream pis = new PipedInputStream();
PipedOutputStream pos = new PipedOutputStream(pis);
button.addActionListener(e -> {
try {
pos.write((int) (Math.random() * 1000));
//records time the packet was sent
millis = System.currentTimeMillis();
} catch (IOException e1) {
e1.printStackTrace();
}
});
while (true) {
System.out
.println("recieved: " + pis.read() + "\n\tin time (ms): " + (System.currentTimeMillis() - millis));
}
}
}
This delay is usually around 300-900 ms for me. This is pretty big in my application. I am wondering why is it this big of a delay? And how can i fix my code to reduce the delay?
Thanks in advance.
Upvotes: 2
Views: 782
Reputation: 44854
The issue is that the output is not being flushed
see http://docs.oracle.com/javase/7/docs/api/java/io/PipedOutputStream.html#flush()
Upvotes: 5