title: Losing data through piped streams in java
body: <p>I'm doing a lab work for my parallel and concurrent programming class in Java. For now, I'm trying to use piped streams to communicate between threads. I'm using PipedWriter and PipedReader from the java.io library. For some reason, some of the message i'm sending through is lost when communicating between the threads.</p>
  
  <p>To be more specific, here's a screenshot. </p>
  
  <p><a href="http://screencloud.net/v/bicK" rel="nofollow">http://screencloud.net/v/bicK</a></p>
  
  <p>As you can see, I'm getting some exotic symbols as well, which doesn't usually bode too well :)</p>
  
  <p>Here's my thread class</p>
  
  <pre><code>package lab2_string;
  
  import java.io.*;
  
  public class StringRunnable implements Runnable{
  
      int threadNr;
      PipedReader in;
      PipedWriter out;
      String msg = "";
      @Override
      public void run() {
          readStream();
          System.out.println("Thread nr: " + threadNr);
          System.out.println("Message: " + msg);
          writeToStream();
      }
  
      public StringRunnable(PipedReader rs, PipedWriter ws, int threadNr){
          try{
              out = ws;
              in = rs;
              this.threadNr = threadNr;
          }catch (Exception e) {
              System.out.println("Error:" + e);
          }
      }
  
      public void writeToStream(){
          try{
              out.write(msg);
              out.flush();
              out.close();
          }catch (Exception e) {
              System.out.println("Error:" + e);
          }
      }
  
  
      public void readStream(){
          try{
              while(in.read()!=-1){
                  char c = (char) in.read();
                  msg = msg + c;
              }in.close();
          }catch (Exception e) {
              System.out.println("Error:" + e);
          }
      }
  
  }
  </code></pre>
  
  <p>And my main program class</p>
  
  <pre><code>package lab2_string;
  
  import java.io.*;
  
  public class Lab2 {
  
      public static void main(String[] args) {
          try{
  
              PipedWriter pwOut1 = new PipedWriter();
              PipedReader pwIn1 = new PipedReader(pwOut1);
              PipedWriter pwOut2 = new PipedWriter();
              PipedReader pwIn2 = new PipedReader(pwOut2);
              PipedWriter pwOut3 = new PipedWriter();
  
              Thread t1;
              Thread t2;
  
              t1 = new Thread(new StringRunnable(pwIn1,pwOut2,1));
              t2 = new Thread(new StringRunnable(pwIn2,pwOut3,2));
              t1.start();
              t2.start();
  
              pwOut1.write("Andrew");
              pwOut1.flush();
              pwOut1.close();
  
  
          }catch (Exception e) {
              System.out.println("Error:" + e);
          }
  
      }
  
  }
  </code></pre>
  
  <p>Please help me understand what's causing this, and how can I fix it !</p>