Javamail读取邮件列表出现OutOfMemery

用Javamail解析多个邮件的时候,如果个别邮件的附件过大,就会造成OutOfMemery的情况,如下

 

Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
	at java.util.Arrays.copyOf(Arrays.java:2786)
	at java.io.ByteArrayOutputStream.write(ByteArrayOutputStream.java:71)
	at com.sun.mail.pop3.Protocol.multilineCommand(Protocol.java:362)
	at com.sun.mail.pop3.Protocol.retr(Protocol.java:237)
	at com.sun.mail.pop3.POP3Message.getContentStream(POP3Message.java:115)
	at javax.mail.internet.MimePartDataSource.getInputStream(MimePartDataSource.java:60)
	at javax.mail.internet.MimeMultipart.parse(MimeMultipart.java:259)
	at javax.mail.internet.MimeMultipart.getCount(MimeMultipart.java:159)
	at com.gdcn.mail.util.Pop3Util.hasAttachment(Pop3Util.java:1148)
	at com.gdcn.mail.util.Pop3Util.analysisMessage(Pop3Util.java:774)
	at com.gdcn.mail.util.Pop3Util.getMessages(Pop3Util.java:561)
	at com.gdcn.mail.util.Pop3Util.main(Pop3Util.java:1338)
 

原因是JavaMail会将这些Messages读入内存,由于这些邮件包含了附件等等,所以会造成这样的结果。

 

网上很多都说增加JVM或者Tomcat等的内存,但是这样仍然不能达到预期的效果。或来查阅了相关的文档和网上的结果,发现了解决这个问题的方法,我们只需要在解析完邮件之后增加这句

 

((POP3Message) message).invalidate(true);

 

sun有这样的解析

http://java.sun.com/products/javamail/javadocs/com/sun/mail/pop3/POP3Message.html

invalidate

public void invalidate
(boolean invalidateHeaders)
Invalidate the cache of content for this message object, causing it to be fetched again from the server the next time it is needed. If invalidateHeaders is true, invalidate the headers as well.

 

Parameters:
invalidateHeaders - invalidate the headers as well?

 

这样就很好地将原来读取的message从cache里面擦除了

你可能感兴趣的:(java,jvm,tomcat,cache,sun)