Reputation: 10203
I'd like to read from a process's output and error streams and merge them into one stream of text. My program is in groovy and reads like this:
def mergeStream = new ByteArrayOutputStream()
process.waitForProcessOutput(mergeStream, mergeStream)
The problem is that ByteArrayOutputStream isn't thread safe and waitForProcessOutput() generates two threads which append to mergeStream. Is there a thread-safe variant that I can use? How else do you recommend that I control access to mergeStream? It looks like in practice characters are sometimes dropped with this implementation.
Upvotes: 9
Views: 3553
Reputation: 691825
If the process.waitForProcessOutput()
takes an OutputStream
as argument, you could simply use a custom implementation of OutputStream
that has all its methods synchronized, and delegate to the corresponding method of a wrapped ByteArrayOutputStream
. Just like Collections.synchronizedList()
wraps another List into a synchronized List proxy.
EDIT:
That said, reading the source of ByteArrayOutputStream, all its methods are already synchronized, so it's already thread-safe. Your bug probably comes from elsewhere.
Upvotes: 7