title: How to clone an inputstream in java in minimal time
body: <p>Can someone tell me how to clone an inputstream, taking as little creation time as possible?  I need to clone an inputstream multiple times for multiple methods to process the IS.  I've tried three ways and things don't work for one reason or another.</p>
  
  <p>Method #1:
  Thanks to the stackoverflow community, I found the following link helpful and have incorporated the code snippet in my program.</p>
  
  <p><a href="https://stackoverflow.com/questions/5923817/how-to-clone-an-inputstream">How to clone an InputStream?</a></p>
  
  <p>However, using this code can take up to one minute (for a 10MB file) to create the cloned inputstreams and my program needs to be as fast as possible.</p>
  
  <pre><code>    int read = 0;
      byte[] bytes = new byte[1024*1024*2];
  
      ByteArrayOutputStream bos = new ByteArrayOutputStream();
      while ((read = is.read(bytes)) != -1)
          bos.write(bytes,0,read);
      byte[] ba = bos.toByteArray();
  
      InputStream is1 = new ByteArrayInputStream(ba);
      InputStream is2 = new ByteArrayInputStream(ba);
      InputStream is3 = new ByteArrayInputStream(ba);
  </code></pre>
  
  <p>Method #2:
  I also tried using BufferedInputStream to clone the IS.  This was fast (slowest creation time == 1ms.  fastest == 0ms).  However, after I sent is1 to be processed, the methods processing is2 and is3 threw an error saying there was nothing to process, almost like all 3 variables below referenced the same IS.</p>
  
  <pre><code>    is = getFileFromBucket(path,filename);
      ...
      ...
      InputStream is1 = new BufferedInputStream(is);
      InputStream is2 = new BufferedInputStream(is);
      InputStream is3 = new BufferedInputStream(is);
  </code></pre>
  
  <p>Method #3:
  I think the compiler is lying to me.  I checked markSupported() for is1 for the two examples above.  It returned true so I thought I could run</p>
  
  <pre><code>    is1.mark() 
      is1.reset()
  </code></pre>
  
  <p>or just</p>
  
  <pre><code>    is1.reset();
  </code></pre>
  
  <p>before passing the IS to my respective methods.  In both of the above examples, I get an error saying it's an invalid mark.</p>
  
  <p>I'm out of ideas now so thanks in advance for any help you can give me.</p>
  
  <p>P.S.  From the comments I've received from people, I need to clarify a couple things regarding my situation:
  1)  This program is running on a VM
  2)  The inputstream is being passed into me from another method.  I'm not reading from a local file
  3)  The size of the inputstream is not known</p>