title: JVM/Tomcat crashes when too many uploads occur in parallel (Heap Space)?
body: <p>I have a Servlet application running on Tomcat 7. I set the following in setenv.sh</p>
  
  <pre><code>CATALINA_OPTS="
  -server 
  -Xms1G 
  -Xmx5G
  -XX:MaxPermSize=512m
  -Dfile.encoding=UTF-8";
  </code></pre>
  
  <p>The server runs on Ubuntu 12.04LTS, has 6 Cores and 8GB of RAM. 
  My application is a Grails/Spring/Java app where users can upload images. Sometime it occurs that 3-5 users start uploading images at the same time. In these situations my Tomcat crashes because of the following error: </p>
  
  <pre><code>java.lang.OutOfMemoryError: Java heap space
  </code></pre>
  
  <p>I know that I have to increase the Xmx parameter of my Tomcat to prevent this problem. But seriously what is wrong in my case? </p>
  
  <ol>
  <li><p>Is there a best practice to handle file uploads like in my scenario? </p></li>
  <li><p>Can I prevent this problem some how? I mean when 5GB are not enough for 3-5 parallel uploads how much resources do I need for hundreds of parallel uploads?</p></li>
  <li><p>Is my app so bad or is it normal that file upload takes so much resources?</p></li>
  </ol>
  
  <p>Note: The files that users upload are 2-8 MB.</p>
  
  <p>This is how I do the upload in my view: </p>
  
  <pre><code>   &lt;g:form method="post" action="save" enctype="multipart/form-data"&gt;
      &lt;input type="file" name="file"/&gt;
      &lt;input type="submit"/&gt;
     &lt;/g:form&gt;
  </code></pre>
  
  <p>and in my Controller: </p>
  
  <pre><code>def file = request.getFile('image')
  byte [] byteFile = file.getBytes()
  </code></pre>
  
  <p>In config/spring/resource.groovy I did:</p>
  
  <pre><code>beans = { 
    multipartResolver(org.springframework.web.multipart.commons.CommonsMultipartResolver){
  
          // Max in memory 100kbytes
          maxInMemorySize=102400
  
      }
  
  } 
  </code></pre>
  
  <p>The uploaded file are images. They will be scaled and saved to disk.</p>
  
  <p>The images will be saved as:</p>
  
  <pre><code>bytes [] currentImage = // some image in bytes ...
  def newFile = new FileOutputStream(fullPath)
  newFile.write(currentImage)
  newFile.close()
  </code></pre>