public static <T> byte[] encodeToByteArray(Coder<T> coder, T value, Coder.Context context) throws CoderException { if (threadLocalOutputStreamInUse.get()) { // encodeToByteArray() is called recursively and the thread local stream is in use, // allocating a new one. ByteArrayOutputStream stream = new ExposedByteArrayOutputStream(); encodeToSafeStream(coder, value, stream, context); return stream.toByteArray(); } else { threadLocalOutputStreamInUse.set(true); try { ByteArrayOutputStream stream = getThreadLocalOutputStream(); encodeToSafeStream(coder, value, stream, context); return stream.toByteArray(); } finally { threadLocalOutputStreamInUse.set(false); } } }