title: ByteArrayOutputStream performance
body: <p>My requirement is to create 2 copies of the inputstream, one for Apache Tika File MimeType Detect and another to Output Stream.</p>
  
  <pre><code>private List&lt;InputStream&gt; copyInputStream(final InputStream pInputStream, final int numberOfCopies) throws UploadServiceException{
      final int bytesSize = 8192;
      List&lt;InputStream&gt; isList = null;        
      try(PushbackInputStream pushIS = new PushbackInputStream(pInputStream);
              ByteArrayOutputStream baos = new ByteArrayOutputStream();){  
          byte[] buffer = new byte[bytesSize];
          for (int length = 0; ((length = pushIS.read(buffer)) &gt; 0);) {
              baos.write(buffer, 0, length);
          }
          baos.flush();
          isList = new ArrayList();
          for(int i = 0; i &lt; numberOfCopies ; i++){
              isList.add(new ByteArrayInputStream(baos.toByteArray()));
          }
      } catch (IOException ex) {
          throw new MyException(ErrorCodeEnum.IO_ERROR, ex);
      } catch (Exception ex) {            
          throw new MyException(ErrorCodeEnum.GENERIC_ERROR, ex);
      }
      return isList;
  }
  </code></pre>
  
  <p>I see some performance issues</p>
  
  <ol>
  <li>The size of the byte array is twice the file size. I planned on using the ByteArrayOutputStream(int size) but I don't have the file size during the upload. </li>
  <li>I see the garbage collection is not happening very often, how does one handle such cases.</li>
  </ol>
  
  <p><strong>UPDATE</strong></p>
  
  <p>Based on the feedback</p>
  
  <ul>
  <li>Removed PushbackInputStream </li>
  <li><p>Added final byte[] byteArrayIS = baos.toByteArray();</p>
  
  <pre><code>private List&lt;InputStream&gt; copyInputStream(final InputStream pInputStream, final int numberOfCopies) throws MyException{
      final int bytesSize = 8192;
      List&lt;InputStream&gt; isList = null;        
      try(ByteArrayOutputStream baos = new ByteArrayOutputStream();){  
          byte[] buffer = new byte[bytesSize];
          for (int length = 0; ((length = pInputStream.read(buffer)) &gt; 0);) {
              baos.write(buffer, 0, length);
          }
          baos.flush();
          isList = new ArrayList();
          final byte[] byteArrayIS = baos.toByteArray();
          for(int i = 0; i &lt; numberOfCopies ; i++){
              isList.add(new ByteArrayInputStream(byteArrayIS));
          }
      } catch (IOException ex) {
          throw new MyException(ErrorCodeEnum.IO_ERROR, ex);
      } catch (Exception ex) {
          if(ex instanceof MyException){
              throw ex;
          }
          throw new MyException(ErrorCodeEnum.GENERIC_ERROR, ex);
      }
      return isList;
  }
  </code></pre></li>
  </ul>