MimeMessage.saveChanges is very slow

The following test takes about 5 seconds to complete due to the inclusion of m.saveChanges() .

 import org.junit.Before; import org.junit.Test; import javax.mail.MessagingException; import javax.mail.Session; import javax.mail.internet.MimeMessage; import java.io.IOException; import java.util.Properties; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @Test public void test1() throws MessagingException, IOException { Session s = Session.getDefaultInstance(new Properties()); MimeMessage m = new MimeMessage(s); m.setContent("<b>Hello</b>", "text/html; charset=utf-8"); m.saveChanges(); assertEquals(m.getContent(), "<b>Hello</b>"); assertEquals(m.getContentType(), "text/html; charset=utf-8"); } 

I also made fun of the session with mockito, but this does not help:

 Session s = mock(Session.class); when(s.getProperties()).thenReturn(new Properties()); 

What is the problem? What can I make fun of to speed up the process?

+1
source share
1 answer

Fix the most common mistakes people make when using JavaMail in their code.

DNS lookups can hurt performance on some machines. For the JDK, you can change the security properties for caching the DNS lookup networkaddress.cache.ttl and networkaddress.cache.negative.ttl or set the system properties sun.net.inetaddr.ttl and sun.net.inetaddr.negative.ttl . The default behavior in JDK 7 and later does a good job of caching.

Preferably, you can use session properties to avoid some of these searches.

Since you cannot transfer the message, apply rule # 2 by changing the code to:

 @Test public void test1() throws MessagingException, IOException { Properties props = new Properties(); props.put("mail.host", "localhost"); //Or use IP. Session s = Session.getInstance(props); MimeMessage m = new MimeMessage(s); m.setContent("<b>Hello</b>", "text/html; charset=utf-8"); m.saveChanges(); assertEquals(m.getContent(), "<b>Hello</b>"); assertEquals(m.getContentType(), "text/html; charset=utf-8"); } 

If you carry the message, then combine the rules # 1, # 2 and # 3, which will prevent access to the host system to search for a name. If you want to prevent all DNS queries during transport, you need to use IP addresses.

+4
source

Source: https://habr.com/ru/post/1435312/


All Articles