Course contentsShow
← Java
Lesson 1940 of 2,87039. File I/O: Basic Byte StreamsFree lesson

Nested Buffering Anti-Pattern: Avoid Double Buffering

Never wrap a BufferedInputStream with another BufferedInputStream; it adds overhead without benefit.

Nested Buffering Anti-Pattern: Avoid Double Buffering

What you'll learn: Why wrapping a BufferedInputStream inside another BufferedInputStream is wasteful and how to avoid this common mistake.

The Core Problem

Now that you understand buffering's performance benefits, there's a critical pitfall to avoid: double buffering. This happens when you accidentally wrap a buffered stream with another buffered stream:

// WRONG - double buffering!
InputStream in = new FileInputStream("data.bin");
BufferedInputStream buffered1 = new BufferedInputStream(in);
BufferedInputStream buffered2 = new BufferedInputStream(buffered1);  // DON'T DO THIS

Why This Is Harmful

Think of it like having two shopping carts while grocery shopping. You fill the small cart, then transfer items to the big cart, then finally to your car. That middle step is pure overhead with no benefit.

Each BufferedInputStream maintains its own 8KB buffer. With two layers:

  • When you call read(), the outer buffer checks its cache
  • If empty, it reads from the inner buffer (8KB at once)
  • The inner buffer then reads from the file (another 8KB)
  • You're copying data from file → inner buffer → outer buffer → your application

This wastes memory (16KB instead of 8KB) and adds processing time moving bytes between buffers unnecessarily. You gain nothing because the inner buffer already solves the system-call problem.

The Right Approach

Wrap the raw stream once:

// CORRECT - single buffering
InputStream in = new FileInputStream("data.bin");
BufferedInputStream buffered = new BufferedInputStream(in);  // Good!

The same applies to output streams—never nest BufferedOutputStream instances.

Key Takeaway: Buffer a raw stream only once; wrapping a buffered stream with another buffer creates wasteful overhead without any performance gain.