views:

4580

answers:

5

Does anyone have any good suggestions for creating a Pipe object in Java which is both an InputStream and and OutputStream since Java does not have multiple inheritance and both of the streams are abstract classes instead of interfaces?

The underlying need is to have a single object that can be passed to things which need either an InputStream or an OutputStream to pipe output from one thread to input for another.

+2  A: 

This is a pretty common thing to do, I think. See this question.

http://stackoverflow.com/questions/43157/easy-way-to-write-contents-of-a-java-inputstream-to-an-ouptutstream#43164

Apocalisp
I know about PipedXxxStream... but I was wanting to create just one Pipe object which could be given as an InputStream to one thread and an OutputStream to another. Was hoping I might have missed something.
Baginsss
Wouldn't be very hard to write something that can give you an inputstream that pipes to an outputstream, but you won't be able to extend both InputStream and OutputStream. Inheritance, bad. Composition, good.
Apocalisp
+4  A: 

java.io.PipedOutputStream and java.io.PipedInputStream look to be the classes to use for this scenario. They are designed to be used together to pipe data between threads.

If you really want some single object to pass around it would need to contain one of each of these and expose them via getters.

mackenir
A: 

You can't create a class which derives both from InputStream and OutputStream because these aren't interfaces and they have common methods and Java doesn't allow multiple inheritance (the compiler doesn't know whether to call InputStream.close() or OutputStream.close() if you call close() on your new object).

The other problem is the buffer. Java wants to allocate a static buffer for the data (which doesn't change). This means when you use the `java.io.PipedXxxStream', the writing data to it will eventually block unless you use two different threads.

So the answer from Apocalisp is correct: You must write a copy loop.

I suggest that you include Apache's commons-io in your project which contains many helper routines just for tasks like this (copy data between streams, files, strings and all combinations thereof).

Aaron Digulla
+3  A: 

It seems the point of this question is being missed. If I understand you correctly, you want an object that functions like an InputStream in one thread, and an OutputStream in another to create a means of communicating between the two threads.

Perhaps one answer is to use composition instead of inheritance (which is recommended practice anyway). Create a Pipe which contains a PipedInputStream and a PipedOutputStream connected to each other, with getInputStream() and getOutputStream() methods.

You can't directly pass the Pipe object to something needing a stream, but you can pass the return value of it's get methods to do it.

Does that work for you?

Software Monkey
A: 

See http://ostermiller.org/utils/CircularBuffer.html