Reading from javamail takes a long time

后端 未结 4 1873
孤城傲影
孤城傲影 2021-02-15 15:57

I use javamail to read mails from an exchage account using IMAP protocol. Those mails are in plain format and its contents are XMLs.

Almost all those mails have short

4条回答
  •  梦谈多话
    2021-02-15 16:59

    It would always be messages[i].getContent() that would be the slowest part of the code. The reason is normally IMAP server would not cache this part of message data. Nevertheless, you can try this:

        FetchProfile fp = new FetchProfile();
            fp.add(FetchProfile.Item.ENVELOPE);
            fp.add(FetchProfileItem.FLAGS);
            fp.add(FetchProfileItem.CONTENT_INFO);
        fp.add("X-mailer");
    
    and after you have specified the fetch profile then you do your search/fetch of messages. 
    

    Basically the concept is that the IMAP provider fetches the data for a message from the server only when necessary. (The javax.mail.FetchProfile is used to optimize this). The header and body structure information, once fetched, is always cached within the Message object. However, the content of a bodypart is not cached. So each time the content is requested by the client (either using getContent() or using getInputStream()), a new FETCH request is issued to the server. The reason for this is that the content of a message could be potentially large, and if we cache this content for a large number of messages, there is the possibility that the system may run out of memory soon since the garbage collector cannot free the referenced objects. Clients should be aware of this and must hold on to the retrieved content themselves if needed.

    By using the above mentioned code snippet you could 'hope' for some speed improvement but it solely depends on your SMTP server if this would work or not. All the big SMTP server do not support this behaviour because of the load issue mentioned in the previous paragraph and hence you may not gain any speed.

提交回复
热议问题