This is an extension of my question posted here, while that seems to have fixed one part of my problem, now I see IO-Exception read end dead exception
. I am using a multithreaded
application where thread-1 produces
random numbers and other thread-2 consumes
it to calculate the average. once the average reaches a threshold, I signal thread-1
to stop producing the numbers. This is the basic design of the code.
I am getting IO-Exception read end dead exception
. I want to know why it comes and how to fix it. Thanks.
The code below :
import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.PipedInputStream; import java.io.PipedOutputStream; import java.util.Random; import java.util.concurrent.atomic.AtomicBoolean; // class NumGen extends Thread { PipedOutputStream pos; DataOutputStream dos; AtomicBoolean isDone; public NumGen(PipedOutputStream pos,AtomicBoolean isDone){ this.pos=pos; dos=new DataOutputStream(pos); this.isDone=isDone; } public void run(){ while (!isDone.get()){ Random rand = new Random(); try { dos.writeDouble(rand.nextDouble()+100.0); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } class RunningAvg extends Thread { PipedInputStream pis; DataInputStream dis; Double avg; int count; Double runningTotal; AtomicBoolean isDone; public RunningAvg(PipedInputStream pis,AtomicBoolean isDone){ this.pis=pis; dis=new DataInputStream(pis); runningTotal=0.0; avg=0.0; this.isDone=isDone; } public void run(){ try { while (dis.available()>0){ count+=1; runningTotal+=dis.readDouble(); avg=runningTotal/count; System.out.printf("The average in count no : %s is %s%n",count,avg); if (avg>1E5) isDone.set(true); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public class InterThreadComm { public static void main(String[] args){ try { PipedOutputStream pos= new PipedOutputStream(); PipedInputStream pis = new PipedInputStream(pos); AtomicBoolean isDone = new AtomicBoolean(false); NumGen ng = new NumGen(pos,isDone); RunningAvg ra = new RunningAvg(pis,isDone); ng.start(); ra.start(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
EDIT: As per the answer below: I tried to close the Streams using try-with-resources. but I get java.io.IOException: Pipe closed
public class InterThreadComm { public static void main(String[] args){ try(PipedOutputStream pos= new PipedOutputStream();PipedInputStream pis =new PipedInputStream(pos)){ AtomicBoolean isDone = new AtomicBoolean(false); NumGen ng = new NumGen(pos,isDone); RunningAvg ra = new RunningAvg(pis,isDone); ng.start(); ra.start(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }