Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a thread-safe ByteArrayOutputStream?

Tags:

java

groovy

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.

like image 670
dromodel Avatar asked Oct 31 '12 21:10

dromodel


1 Answers

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.

like image 158
JB Nizet Avatar answered Nov 18 '22 05:11

JB Nizet