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.
If the
process.waitForProcessOutput()takes anOutputStreamas argument, you could simply use a custom implementation ofOutputStreamthat has all its methods synchronized, and delegate to the corresponding method of a wrappedByteArrayOutputStream. Just likeCollections.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.