OutOfMemoryError with javamail getmessage
Hello
In a java program, i want for statistics purpose, read one by one all messages from a Mail
Folder (it has a million messages but each of them is less than 5k).
However, after the program has retrieved a number of messages (in my case about 20000 messages),
i get an OutOfMemoryError. Even when i force a Runtime or System gc every 1000 messages,
the result is the same; it seems that garbage collection is not working and the retrieved
(and no longer used) previous messages or strings do not get freed.
Does anyone know how the program could be rewritten so that gc works and i do not get the
OutOfError?
The only workarround i found is, after every 1000 messages, to close the mail Folder, and
immediately open it again to read the next part of the messages.
Bellow is a portion of my program.
import java.io.*;
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
public class Mail {
public static void main(String[] argv) {
int mTotal=0,mCount;
Properties mProps = System.getProperties();
mProps.put("mail.imap.timeout", "300000");
Session mSession = Session.getInstance(mProps, null);
Store mStore = null;
Folder mFolder = null;
try {
mStore = mSession.getStore(new URLName("imap://user:password@mail.com"));
mStore.connect();
mFolder = mStore.getFolder("Inbox");
mFolder.open(Folder.READ_ONLY);
mTotal = mFolder.getMessageCount();
}
catch (Exception e) {System.out.println(""+e); System.exit(1); }
System.out.println("Total msg:"+mTotal);
Calendar mCalBegin=Calendar.getInstance();
mCalBegin.set(2008,5,1,0,0,0);
Calendar mCalEnd=Calendar.getInstance();
mCalEnd.set(2008,6,1,0,0,0);
for(mCount=1;mCount<=mTotal;mCount++) {
if(mCount%1000==0) {
try {
mFolder.close(false);
mFolder = mStore.getFolder("Inbox");
mFolder.open(Folder.READ_ONLY);
}
catch(Exception e){System.out.println("Error\n"+e);System.exit(1);}
System.out.println("Cnt "+mCount+", Free "+Runtime.getRuntime().freeMemory());
}
try {
Message mMsg = mFolder.getMessage(mCount);
Calendar mCalMsg = Calendar.getInstance();
mCalMsg.setTime(mMsg.getSentDate());
if(mCalBegin.before(mCalMsg) & mCalEnd.after(mCalMsg)) {
String mSubject = mMsg.getSubject();
String mFrom = mMsg.getFrom()[0].toString().toLowerCase();
String mTo =mMsg.getRecipients(Message.RecipientType.TO)[0].toString().toLowerCase();
System.out.println(mFrom+";"+mTo+";"+mSubject);
}
}
catch(Exception e){System.out.println("Error\n"+e);System.exit(1);}
}
try {
mFolder.close(false);
mStore.close();
}
catch(Exception e){ System.out.println("Error\n"+e);}
}
}
PS: if you want to reply to my mail adress, remove the xs.