0

I am trying to understand piped streams. Instead of piped stream why can't we use other streams to pipe each other? like below:

final ByteArrayOutputStream pos = new ByteArrayOutputStream();

final ByteArrayInputStream pis = new ByteArrayInputStream(pos.toByteArray());

and when will we have a deadlock in a piped stream? I tried to read and write using single main thread, but it executes smoothly.

Mureinik
  • 297,002
  • 52
  • 306
  • 350

2 Answers2

0

The difficulty here is that the process must be implemented in several threads because writing to one end of the pipe must be matched with a read at the other end.

It is certainly not difficult to create a thread to monitor arrivals at the end of one pipe and push them back through another pipe but it cannot be done with a single thread.

Have you looked at this question?

Community
  • 1
  • 1
OldCurmudgeon
  • 64,482
  • 16
  • 119
  • 213
0

Piped streams allow for efficient byte-by-byte processing with minimal effort.

I could very well be wrong, but I believe toByteArray() might not do what you think it does. It just copies the current contents, not any contents in future.

So the only real issue here is management of this, which would be a bit more difficult. You'd have to constantly poll the output stream. Not to mention the memory allocation of an array for each call to toByteArray (which "Creates a newly allocated byte array" for each call).

How I suspect deadlocks may happen in a single thread:

If you try to (blocking) read from an input stream that doesn't have data yet. It will never be able to get data because data can only be obtained from the output stream to which must be written in the same thread, which can't happen while you're sitting waiting for data.

So, in a single thread, it will happen if you're not very careful, but it should be possible to successfully use them in the same thread without deadlocks, but why would you want to? I think another data structure may be better suited, like a linked-list or simple circular array.

Bernhard Barker
  • 54,589
  • 14
  • 104
  • 138