title: Fastest way to GZIP and UDP a large amount of Strings in Java
body: <p>I'm implementing a logging system that needs to encode the log messages with GZIP and send them off by UDP.</p>
  
  <p>What I've got so far is:</p>
  
  <p>Initialization:</p>
  
  <pre><code>DatagramSocket sock = new DatagramSocket(); 
  baos = new ByteArrayOutputStream();
  printStream = new PrintStream(new GZIPOutputStream(baos));
  </code></pre>
  
  <p>This printStream is then passed out of the logger - messages will arrive through it</p>
  
  <p>Then every time a message arrives:</p>
  
  <pre><code>byte[] d = baos.toByteArray();
  DatagramPacket dp = new DatagramPacket(d,d.length,host,port);
  sock.send(dp);
  </code></pre>
  
  <p>What stumps me currently is that I can't find a way to remove the data from the ByteArrayOutputStream (toByteArray() only takes a copy) and I'm afraid that recreating all three stream objects every time will be inefficient.</p>
  
  <p>Is there some way to remove sent data from the stream? Or should I look in another direction entirely?</p>