user1040283
user1040283

Reputation: 13

How do I connect a PipedReader to a PipedWriter while they are on different threads?

As title says, mock code to demostrate my problem

Driver Class

  import java.io.*;

    public class driver
    {

        public static void main(String[] args)
        {
            PipedWriter writer1 = new PipedWriter();
            PipedWriter writer2 = new PipedWriter();
            PipedReader reader1 = new PipedReader();
            PipedReader reader2 = new PipedReader();

            Thread thread1 = new MyThread(writer1, reader1);
            Thread thread2 = new MyThread(writer2, reader2);
            try
            {
                  writer2.connect(reader1);
             } catch(Exception e)
             {
                  e.printStackTrace();
             }
        }
    }

MyThread Class

 import java.io.*;
public class MyThread extends Thread
{
    PipedReader input = new PipedReader();
    PipedWriter output = new PipedWriter();

    public MyThread(PipedWriter input, PipedReader output)
    {
        try
        {
            this.input.connect(input);
            this.output.connect(output);
        } catch(Exception e)
        {
            e.printStackTrace();            
               }
    }
    public void run()
    {
        try
        {
            input.close();
            output.close();
        }catch(Exception e)
        {
            e.printStackTrace();
        }
    }
}

I'm not sure if the .connect method is what I should be using. What I want to do is have the output stream coming from the first thread writing straight into the input stream of the second.

The code above compiles fine but says its already connected otherwise.

java.io.IOException: Already connected
        at java.io.PipedWriter.connect(Unknown Source)
        at driver.main(driver.java:17)

Upvotes: 1

Views: 978

Answers (2)

Perception
Perception

Reputation: 80603

You are doing some unnecessary initialization for the writers and readers in your Thread class. Just hook up the instances passed into your constructor and wire them up. Pseudocode:

import java.io.*;
public class MyThread extends Thread
{
    PipedReader input = null;
    PipedWriter output = null;

    public MyThread(PipedWriter input, PipedReader output)
    {
        this.input = input;
        this.output = output;

        this.output.connect(input);
    }
}

Read up on PipedWriter's and Readers here.

Upvotes: 0

JB Nizet
JB Nizet

Reputation: 691785

If a writer is connected to a reader, the reader is also connected to the writer. You don't need to connect them twice. And if one thread writes and the other reads, you just need one writer and one reader.

Create both in the main thread, connect them, then creat one thread with the reader and one with the writer, and start both threads.

Upvotes: 2

Related Questions