Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's implicit contracts of the filter streams in java?

Tags:

I am reading a book 'Java Network Programming (Elliotte Rusty Harold)'. And I met the following sentence, after this code.

FileInputStream fin = new FileInputStream("data.txt");
BufferedInputStream bin = new BufferedInputStream(fin);

...intermixing calls to different streams connected to the same source may violate several implicit contracts of the filter streams.

And the following code came out.

InputStream in = new FileInputStream("data.txt");
in = new BufferedInputStream(in);

I understand that this simplifies the syntax, but I wonder what 'several implicit contracts of the filter streams' means.

like image 351
Changsu Avatar asked Aug 05 '19 19:08

Changsu


1 Answers

If multiple filter streams are connected to the same source stream, then those filter streams may behave in incompatible ways. Imagine, as a hypothetical, two streams:

  • BufferedInputStream: A stream filter that contains a buffer (e.g. to coalesce reads)
  • NoChangeInputStream: In my example, I don't even need a special behavior for one of my filter streams. This class just delegates all I/O to the underlying input stream, with no filtering.

Now imagine running the following code:

InputStream in = new FileInputStream("data.txt");
BufferedInputStream buf = new BufferedInputStream(in);
NoChangeInputStream nop = new NoChangeInputStream(in);
int byte0 = buf.read();
int byte1 = nop.read();

You would expect that byte1 contains the second byte of the file, but this is incorrect. The BufferedInputStream consumed much more than one byte, when it first filled its buffer, and hence one's typical implicit assumptions about how streams ought to behave, are violated.

This is not the only example by far--consider as well a case where two distinct buffered input streams are consuming the same input file--it's not clear which of the two buffers will get any particular byte, even though the order in which you read from the buffers is clear.

like image 105
nanofarad Avatar answered Oct 02 '22 00:10

nanofarad