I want to know Advantages to use BlockingQueue
instead of (PipedOutputStream
and PipedInputStream
)
import java.io.*;
i
Like any Java Collection
, a BlockingQueue
stores references to objects, so the thread(s) retrieving objects from it receive precisely the same runtime objects, the producing thread(s) put into it.
In contrast, Serialization stores a persistent form into the byte stream, which only works for Serializable
objects and will lead to the creation of copies at the receiving end. In some cases, the objects may get replaced by canonical objects afterwards, still, the entire procedure is significantly more expensive than just transferring references.
In your example case, where you transfer int
values, the object identity doesn’t matter, but the overhead of boxing, serializing, deserializing, and unboxing Integer
instances is even more questionable.
If you didn’t use Serialization, but transferred int
values as four byte
quantities directly, using PipedOutputStream
and PipedInputStream
had a point, as it is a good tool for transferring large quantities of primitive data. It also has an intrinsic support for marking the end of data by closing the pipe.
These pipes would also be the right tool for software that ought to be agnostic regarding processes or even the computers running the producer or consumer, i.e. when you want to be able to use the same software when the pipe is actually between processes or even a network connection. That would also justify using Serialization (as JMX connections do).
But unless you’re truly transferring single bytes that retain their meaning when being torn apart, there’s the intrinsic limitation that only one producer can write into a pipe and only one consumer can read the data.