1
val baos = new ByteArrayOutputStream(input.size)
val gzipOut = new GZIPOutputStream(baos)
try {
  gzipOut.write(input.getBytes("UTF-8"), 0, input.length)
  gzipOut.finish()
} finally {
  gzipOut.close()
}

baos.toByteArray

I am trying to compress some data using java gzipoutputstream - it wraps bytearrayoutputstream. is gzipOut.write blocking operation? The gzip out ultimately writes data in memory (and not over disk/network). SO can this or any operation written in above code block the thread of execution?

Note: i am using the above code in scala which is essentially non-blocking application.

acorntech
  • 53
  • 8
  • 1
    No it's not blocking, it's just writing into memory and you have ample space. Could use `try-with-resources` to make it prettier though. `try(val gzipOut = new GZIPOutputStream(baos)) { ...`. – Kayaman Apr 18 '22 at 16:46
  • @Kayaman i suspect so. but the official doc says `Writes array of bytes to the compressed output stream. This method will block until all the bytes are written. Params: buf – the data to be written off – the start offset of the data len – the length of the data Throws: IOException – If an I/O error has occurred.` Can you share some doc for what you mentioned – acorntech Apr 18 '22 at 16:50
  • 1
    That applies for most streams yes, but some special cases such as memory streams or nul streams, it doesn't really make sense. But in the literal sense it does block until all the bytes are written *into memory*, it doesn't perform some kind of async memory write. – Kayaman Apr 18 '22 at 16:58
  • It is blocking but it's not really considered blocking in the sense that it's not doing IO with the filesystem or the network. The real question is how are you using this piece of code? – Gaël J Apr 18 '22 at 19:41
  • @GaëlJ I am using this code to compress data . After the compression is done, it will be sent over the wire – acorntech Apr 18 '22 at 20:02
  • I meant what size is the data? – Gaël J Apr 19 '22 at 17:27

0 Answers0