Re-using Chronicle Bytes' OutputStream

182 views Asked by At

I'm utilizing a third party binary encoder that takes an OutputStream. I retrieve the OutputStream from a Marshallable's writeMarshallable method similar to this:

public void writeMarshallable(WireOut wire) {
    OutputStream outputStream = wire.bytes().outputStream();
    // third party code gets the outputStream, etc.
}

wire.bytes().outputStream()'s implementation creates a new StreamingOutputStream on each invocation, which is what I'm hoping to avoid (superfluous object allocation when the underlying Bytes hasn't actually changed).

That said, I'm thinking about storing a WeakReference to the given wire.bytes() value and checking to see if the provided value reference (ie, ==) is identical to the previously provided value:

private WeakReference<Bytes<?>> priorBytesRef = new WeakReference<>(null);

public void writeMarshallable(WireOut wire) {
    Bytes<?> bytes = wire.bytes();
    if (bytes != priorBytesRef.get()) {
        priorBytesRef = new WeakReference<>(bytes);
        thirdPartyEncoder = EncoderFactoryExample.from(bytes.outputStream());
    }
    // utilize thirdPartyEncoder, etc.
}

So my question is whether this is a reasonable approach or if you Chronicle folks have a more advisable way?

thanks!!

1

There are 1 answers

9
Peter Lawrey On

I suggest using a ThreadLocal to save a StreamingOutputStream.

static final ThreadLocal<StreamingOutputStream> bosTL = ThreadLocal.withInitial(StreamingOutputStream::new);

public void writeMarshallable(WireOut wire) {
    OutputStream out = bosTL.get().init(wire.bytes());
    // utilize thirdPartyEncoder, etc.
}