Java uploads a large file and reports a null pointer, memory overflow error java.lang.OutOfMemoryError solution

Recently, the project has been reporting a null pointer when uploading large files, and then tracking the code to find that when uploading, the I/O flow reported a java.lang.OutOfMemoryError error, which is the problem of memory overflow.
The specific error location:

while ((length = is.read(buffer)) != -1) {
    
    
                ds.write(buffer, 0, length);
            }

Illustration:
insert image description here
When you encounter this situation, you need to check one by one. First, check whether the limit on the file upload size in the SpringMvc configuration file is too small to meet the requirements.

<bean id="multipartResolver"
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
         <!-- maxUploadSize 允许上传的最大文件 200M(200*1024*1024)b为单位 -->
         <property name="maxUploadSize" value="209715200"/>
          <!-- maxInMemorySize允许的最大内存大小 -->
         <property name="maxInMemorySize" value="4096"/>
           <!-- defaultEncoding上传文件编码 -->
         <property name="defaultEncoding" value="UTF-8"/>
          <!-- 设置是否在时惰性地解析多部分,用来抛异常用的,可有可无 -->
         <property name="resolveLazily" value="true"/>
     </bean>

If there is no problem after checking the configuration file, then check whether the tomcat JVM memory setting is too small to cause memory overflow.
After investigation, I found that the JVM memory setting of my tomcat was too small, which caused a memory overflow problem when uploading large files.
My solution is: Increase the JVM memory of tomcat
Modify the content of catalina.bat in apache-tomcat_8082\apache-tomcat-8.0.53\bin
Increase the memory to 1024M
Note: The default in tomcat8.0.5 is:

set "JAVA_OPTS=%JAVA_OPTS% -server -Xms256m -Xmx256m -XX:PermSize=64M -XX:MaxNewSize=256m -XX:MaxPermSize=256m"

change into:

set "JAVA_OPTS=%JAVA_OPTS% -server -Xms1024m -Xmx1024m -XX:PermSize=512M -XX:MaxNewSize=512m -XX:MaxPermSize=512m"

Illustration:
insert image description here
When solving this problem, the blogs of two developers gave a lot of inspiration, and the positioning of the problem was relatively accurate. Although it did not solve my problem, it was very useful for reference.
https://blog.csdn.net/dongbang111/article/details/43919731
https://blog.csdn.net/magiccity/article/details/83008285

Guess you like

Origin blog.csdn.net/Acompanys/article/details/105434370