title: What is the root cause of getting Out Of Memory Exception? How can we overcome this?
body: <p>Here is my sample snippet for reading and writing by output stream and I am getting out of memory exception.</p>
  
  <pre><code> public static void readFileContent(InputStream in, OutputStream out) throws IOException {
      byte[] buf = new byte[500000];
      int nread;
      int navailable;
      int total = 0;
      synchronized (in) {
          try {
              while((nread = in.read(buf, 0, buf.length)) &gt;= 0) {
                  out.write(buf, 0, nread);
                  total += nread;
              }
          }
          finally {
              if (in != null) {
                  try {
                      in.close();
                  } catch (Exception e) {
                      e.printStackTrace();
                  }
              }
          }
      }
  
      out.flush();
      buf = null;
  }
  </code></pre>
  
  <blockquote>
    <ol>
    <li>What are the possible scenarios with the above snippet to get "out of memory exception" ?</li>
    <li>Is it necessary to close the output stream here? And does stream, flush is enough or do we need to close the stream always? If so why?</li>
    <li>How could I avoid Out of memory exception in general?</li>
    </ol>
  </blockquote>
  
  <p>Please clarify me.</p>