r/javahelp • • Feb 13 '20

What the freak are buffered readers?

Can someone help me and tell me what exactly it does? Thanks

16 Upvotes

6 comments sorted by

23

u/Northeastpaw Feb 13 '20

A non-buffered reader will read one byte at a time from the underlying source. Depending on the source reading byte-by-byte is really slow.

To improve performance a buffered reader will read some amount of bytes into memory during the first read for one byte. Subsequent reads will read from this buffer until the buffer is empty. Then the reader will grab more data from the underlying source and put it into the buffer. This can drastically improve read performance at the cost of additional memory usage.

6

u/Orffyreus Feb 13 '20

... Subsequent reads will read from this buffer until the buffer is empty. Then the reader will grab more data from the underlying source and put it into the buffer. ...

Is it really like this or is there an attempt to keep the buffer filled (like in media players) so the reading speed has more or less a constant rate?

12

u/Northeastpaw Feb 13 '20

The buffer is refilled as needed. It does not preemptively fill the buffer because there is no guarantee another read will take place.

EDIT: Technically this is implementation dependent. OpenJDK does not do preemptive fills.

1

u/Orffyreus Feb 13 '20

Oh yes, of course. I forgot about reading manually with buffers. You use them with power of two sizes that are more or less multiples of block sizes, so the memory is used more efficiently without wasting empty space in blocks.

3

u/Jarl-67 Feb 13 '20

Media players need the output to be at a constant rate not the reading.

2

u/caboosetp Private Java/Code Tutor Feb 13 '20

Yeah but that's a different idea than what he was saying.

Media players won't wait until they are empty to get more data, they will try to keep the buffer filled well ahead of current playback to avoid interruptions.

That also doesn't mean it's constant either. The media player might load 30 seconds at a time but wait till there are 10 seconds left before loading the next chunk.