Commit 3e49347
committed
docs(io): add detailed explanation of Piped Streams for inter-thread communication
What
- Documented concept of **Piped Streams in Java** (PipedInputStream + PipedOutputStream).
- Covered:
- Definition and purpose (inter-thread data communication).
- Core components and their roles.
- Step-by-step working mechanism (producer → output stream → internal buffer → input stream → consumer).
- Blocking behavior when buffer is empty/full.
- Stream connection requirement using `.connect()`.
- Listed **advantages** (efficiency, no shared memory, producer-consumer handling).
- Highlighted **disadvantages** (blocking, exception handling, limited buffer).
Why
- Piped Streams are a foundational Java I/O mechanism for **producer-consumer problems** and inter-thread communication.
- Unlike shared memory approaches, they allow **direct streaming of data between threads**.
- Understanding their blocking nature and buffer limitations is crucial for writing safe concurrent programs.
Logic
1. **Producer writes to PipedOutputStream**
- Data is stored in the pipe’s internal buffer.
- If buffer is full → producer thread blocks until space is available.
2. **Consumer reads from PipedInputStream**
- Retrieves bytes from the internal buffer.
- If buffer is empty → consumer thread blocks until producer writes data.
3. **Connection**
- Must explicitly connect `PipedInputStream` with `PipedOutputStream` via `.connect()` before usage.
- Once connected, data flows seamlessly across threads.
4. **Thread Synchronization**
- The blocking nature implicitly synchronizes producer and consumer threads.
- Prevents data corruption without needing explicit locks.
Real-world applications
- **Producer-Consumer problems**: logging systems, event pipelines, data streaming tasks.
- **Multithreaded processing**: one thread generates data (producer), another processes it (consumer).
- **Simulation of Unix-like pipes** in Java programs.
- **Messaging systems** within applications where lightweight communication is needed without shared variables.
Notes
- Buffer size is fixed (default 1024 bytes unless specified).
- Exceptions (e.g., IOException, Pipe broken) must be handled to avoid thread crashes.
- Avoid connecting multiple input/output streams to the same pipe — unsupported and error-prone.
- Works only for **intra-process thread communication** (not across JVMs or machines).
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent 82556ae commit 3e49347
File tree
1 file changed
+1
-1
lines changed- Java 8 Crash Course/Java 8 Streams/Piped Streams/src
1 file changed
+1
-1
lines changedLines changed: 1 addition & 1 deletion
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
47 | 47 | | |
48 | 48 | | |
49 | 49 | | |
50 | | - | |
| 50 | + | |
0 commit comments