Skip to content

Threads leak when SMTP server terminates connections after no DATA is sent (421 error) #387

Closed

Description

@jllanes3

If the SMTP server terminates connections in the pool say after 10 seconds due to their own server policy, client side experiences the following exceptions:

org.simplejavamail.mailer.internal.MailerException: Failed to send email [<77c9d59f-d4cc-4a4c-b5c9-dd284269e58f.1645578246183@[192.168.1.123]>], reason: Third party error
	at org.simplejavamail.mailer.internal.SendMailClosure.handleException(SendMailClosure.java:97)
	at org.simplejavamail.mailer.internal.SendMailClosure.executeClosure(SendMailClosure.java:89)
	at org.simplejavamail.mailer.internal.AbstractProxyServerSyncingClosure.run(AbstractProxyServerSyncingClosure.java:56)
	at org.simplejavamail.internal.util.concurrent.NamedRunnable.run(NamedRunnable.java:41)
	at java.util.concurrent.CompletableFuture$AsyncRun.run(CompletableFuture.java:1640)
	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
	at java.lang.Thread.run(Thread.java:748)
Caused by: com.sun.mail.smtp.SMTPSendFailedException: 421 Timeout waiting for data from client.

	at com.sun.mail.smtp.SMTPTransport.issueSendCommand(SMTPTransport.java:2374)
	at com.sun.mail.smtp.SMTPTransport.mailFrom(SMTPTransport.java:1808)
	at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:1285)
	at org.simplejavamail.mailer.internal.util.TransportRunner.lambda$sendMessage$0(TransportRunner.java:48)
	at org.simplejavamail.mailer.internal.util.TransportRunner.sendUsingConnectionPool(TransportRunner.java:78)
	at org.simplejavamail.mailer.internal.util.TransportRunner.runOnSessionTransport(TransportRunner.java:64)
	at org.simplejavamail.mailer.internal.util.TransportRunner.sendMessage(TransportRunner.java:47)
	at org.simplejavamail.mailer.internal.SendMailClosure.executeClosure(SendMailClosure.java:84)
	... 6 common frames omitted

From then on, I see threads leaking, specially if the pool is configured with 100 core connections (the higher the worse). I think this is due to how the library handles the object pool during some connections in the pool experiencing failures.
image

I have resorted to changing the settings
from:

withConnectionPoolCoreSize: 5
withConnectionPoolMaxSize: 10
withConnectionPoolClaimTimeoutMillis: 5
withConnectionPoolExpireAfterMillis: 15

to:

withConnectionPoolCoreSize: 0
withConnectionPoolMaxSize: 10
withConnectionPoolClaimTimeoutMillis: 5
withConnectionPoolExpireAfterMillis: 5

The reason is:

  1. Stop the create/delete cycle of connections in the pool (since the core size is now 0). This prevents the ever increasing leak.
  2. Recycle any connections within 5 seconds as supposed to letting them reach the 10 second server 421). This removes the error path and therefore the leak.

With such changes, I have not observed the thread leak anymore, however the server timeout could still happen, and I would like to have connections in the pool warmed up (i.e. have a core count) with proper handling during failure modes.

Libraries I am using:

<dependency>
        <groupId>com.sun.mail</groupId>
        <artifactId>javax.mail</artifactId>
        <version>1.6.2</version>
      </dependency>
      <dependency>
        <groupId>com.sun.mail</groupId>
        <artifactId>jakarta.mail</artifactId>
        <version>1.6.5</version>
      </dependency>
      <dependency>
        <groupId>org.simplejavamail</groupId>
        <artifactId>simple-java-mail</artifactId>
        <version>6.6.1</version>
      </dependency>
      <dependency>
        <groupId>org.simplejavamail</groupId>
        <artifactId>core-module</artifactId>
        <version>6.6.1</version>
      </dependency>
      <dependency>
        <groupId>org.simplejavamail</groupId>
        <artifactId>batch-module</artifactId>
        <version>6.6.1</version>
      </dependency>

I did see this, which is very similar:
bbottema/generic-object-pool@6a5684a

But the library version we are using is > 6.0.2, so the issue above is fixed in the version. we use. I think this may be another code path where the leak can happen.

I also tried the latest libraries across the board (7.1.0), and the issue is reproducible just the same.

Activity

  1. bbottema commented on Mar 18, 2022

    @bbottema
    Owner

    Do you have some sample code with which to reproduce the problem your use case?

  2. jllanes3 commented on Mar 19, 2022

    @jllanes3
    Author

    Here is one way I reproed this. Essentially, here are conditions:

    • Hit an SMTP server that expires connections every 10 seconds on server side (this will trigger the "421 Timeout waiting for data from client" exception in the original post)
    • Set the connection expiration time to 15 seconds (above the server timeout of 10 seconds)
    • Set the connection pool to min 100 and max 100 (this will attempt to keep the connection pool)
    • Send 100 emails batch every 60 seconds. This is to ensure the 10 seconds and 15 seconds both get hit.

    Here are the results:
    image
    image

    @Slf4j
    public class SimpleJavaMailApis {
    
        @Test
        @SneakyThrows
        public void test() {
            // setup
            final Properties credentials = loadCredentialsFromFile("file");
            final Mailer mailer = createMailer("smtp-server-endpoint", 587,
                    credentials.getProperty("username"), credentials.getProperty("password"));
            final Email email = EmailBuilder.startingBlank()
                    .from("test@email.com")
                    .to("test@email-blackhole.com")
                    .withSubject("Test subject")
                    .withPlainText("Test body")
                    .fixingMessageId(UUID.randomUUID().toString())
                    .buildEmail();
    
            // execute
            sendEmails(email, mailer, 1);    // warm up?
            TimeUnit.MINUTES.sleep(1);
    
            final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(10);
            scheduler.scheduleAtFixedRate(() -> sendEmails(email, mailer, 100), 0, 60, TimeUnit.SECONDS);
    
            TimeUnit.HOURS.sleep(1);
        }
    
        private void sendEmails(Email email, Mailer mailer, int count) {
            IntStream.range(0, count).forEach(i -> {
                try {
                    final AsyncResponse asyncResponse = mailer.sendMail(email, true);
                    asyncResponse.onSuccess(() -> {
                        log.info("Send succeeded");
                    });
                    asyncResponse.onException(throwable -> {
                        log.error("Send failed");
                    });
                } catch (Exception ex) {
                    log.error("Failed to send email", ex);
                }
            });
        }
    
        private Mailer createMailer(String emailServiceEndpoint,
                                    int port,
                                    String userName,
                                    String password) {
    
            return MailerBuilder
                      // session
                      .withSMTPServer(emailServiceEndpoint, port, userName, password)
                      .withTransportStrategy(TransportStrategy.SMTP_TLS)
                      // timeouts: affects socket connect-, read- and write timeouts
                      .withSessionTimeout(5_000)
    
                      // threads
                      // multi-threaded batch handling
                      .withThreadPoolSize(10)
                      .withThreadPoolKeepAliveTime(60_000)
    
                      // transport connections
                      // keep X transport connections up at all times, automatically refreshed after expiry policy closes it
                      .withConnectionPoolCoreSize(100)
                      // scale up to max X transport connections until expiry policy kicks in and cleans up
                      .withConnectionPoolMaxSize(100)
                      // wait max X millis for available connection (default forever)
                      .withConnectionPoolClaimTimeoutMillis(5_000)
                      // keep transport connections spinning for X millis
                      .withConnectionPoolExpireAfterMillis(15_000)
    
                      .withDebugLogging(false)
                      .withProperty("mail.smtp.ssl.protocols", "TLSv1.2")
      
                      .async()
                      .buildMailer();
        }
    }
    

    Same library version as the original post.
    Same error as before is observed every 60 minutes, but pasting again just in case.

    15:07:35.870 [Simple Java Mail async mail sender, executor 1 / thread 2] ERROR org.simplejavamail.mailer.internal.AbstractProxyServerSyncingClosure - Failed to send email:
    9de092c6-24b9-4619-a80c-e547afef5414
    15:07:35.871 [Simple Java Mail async mail sender, executor 1 / thread 2] ERROR org.simplejavamail.internal.util.concurrent.AsyncOperationHelper - Failed to run sendMail process
    org.simplejavamail.mailer.internal.MailerException: Third party error
    	at org.simplejavamail.mailer.internal.SendMailClosure.executeClosure(SendMailClosure.java:91)
    	at org.simplejavamail.mailer.internal.AbstractProxyServerSyncingClosure.run(AbstractProxyServerSyncingClosure.java:56)
    	at org.simplejavamail.internal.util.concurrent.AsyncOperationHelper$1.run(AsyncOperationHelper.java:75)
    	at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    	at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    	at java.lang.Thread.run(Thread.java:748)
    Caused by: com.sun.mail.smtp.SMTPSendFailedException: 421 Timeout waiting for data from client.
    
    	at com.sun.mail.smtp.SMTPTransport.issueSendCommand(SMTPTransport.java:2358)
    	at com.sun.mail.smtp.SMTPTransport.mailFrom(SMTPTransport.java:1823)
    	at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:1300)
    	at org.simplejavamail.mailer.internal.util.TransportRunner$1.run(TransportRunner.java:52)
    	at org.simplejavamail.mailer.internal.util.TransportRunner.sendUsingConnectionPool(TransportRunner.java:86)
    	at org.simplejavamail.mailer.internal.util.TransportRunner.runOnSessionTransport(TransportRunner.java:72)
    	at org.simplejavamail.mailer.internal.util.TransportRunner.sendMessage(TransportRunner.java:48)
    	at org.simplejavamail.mailer.internal.SendMailClosure.executeClosure(SendMailClosure.java:82)
    	... 7 common frames omitted
    
  3. bbottema commented on Mar 20, 2022

    @bbottema
    Owner

    This is very puzzling indeed, the threads are clearly finishing, yet they are kept around by the executorService. I've run through all the code (without debugger) and it all looks solid to me. Must be some edge case race condition or something.

  4. jllanes3 commented on Mar 20, 2022

    @jllanes3
    Author

    Interestingly, in the code above, if I change the thread pool size setting:

    // from
    .withThreadPoolSize(10)
    // to
    .withThreadPoolSize(50)
    

    You can see the steps in the graph go from 10, to 50.
    // from 10
    image

    // to 50
    image

    There is a correlation between the number of core sender threads (thread pool size) and the amount of connection pool threads leaking.
    image
    ... (other threads in between)
    image

  5. jllanes3 commented on Mar 26, 2022

    @jllanes3
    Author

    Here is what I think the bug is:
    The AutoAllocatorDeallocator pool-1-thread-1 is dying, silently, and no more deallocations are happening past that.
    That class is in charge of cleaning items in this list:
    @NotNull private final LinkedList<PoolableObject> waitingForDeallocation = new LinkedList<>();

    Once that thread dies, that list continues to grow forever, no deallocations occur. The fix should be to simply catch that exception and handle it. Also, any background thread in general needs to have a solid try/catch in its run method so that it does not silently dies forever, or at the very list print that you are allowing it to die forever with a reason why. The code below is not protected against exceptions bubbling up.

    		@Override
    		@SuppressFBWarnings(value = "NP_NULL_ON_SOME_PATH", justification = "False positive")
    		public void run() {
    			//noinspection ConstantConditions
    			while (shutdownSequence == null || !shutdownSequence.isDone() || !waitingForDeallocation.isEmpty()) {
    				allocatedCorePoolAndDeallocateOneOrPlanDeallocations();
    			}
    			log.debug("AutoAllocatorDeallocator finished");
    		}
    

    You can follow the 0,1,2,3,4 steps below.

    	public GenericObjectPool(final PoolConfig<T> poolConfig, @NotNull final Allocator<T> allocator) {
    		this.poolConfig = poolConfig;
    		this.allocator = allocator;
    		poolConfig.getThreadFactory().newThread(new AutoAllocatorDeallocator()).start(); // 0- This is there pool-1-thread-1 is created, which allocates the initial pool, and deallocates later on
    	}
    
    private class AutoAllocatorDeallocator implements Runnable {
    		@Override
    		@SuppressFBWarnings(value = "NP_NULL_ON_SOME_PATH", justification = "False positive")
    		public void run() {
    			//noinspection ConstantConditions
    			while (shutdownSequence == null || !shutdownSequence.isDone() || !waitingForDeallocation.isEmpty()) {
    				allocatedCorePoolAndDeallocateOneOrPlanDeallocations(); // 4- exception bubbles up and kills thread silently, forever
    			}
    			log.debug("AutoAllocatorDeallocator finished");
    		}
    		
    		private void allocatedCorePoolAndDeallocateOneOrPlanDeallocations() {
    			boolean deallocatedAnObject = false;
    			lock.lock();
    			try {
    				while (getCurrentlyAllocated() < poolConfig.getCorePoolsize() && !isShuttingDown()) {
    					available.addLast(new PoolableObject<>(GenericObjectPool.this, allocator.allocate()));
    					totalAllocated.incrementAndGet();
    				}
    				if (!waitingForDeallocation.isEmpty()) {
    					deallocate(waitingForDeallocation.remove());   // 3- exception bubbles up
    					deallocatedAnObject = true;
    				}
    			} finally {
    				lock.unlock();
    			}
    			if (!deallocatedAnObject) {
    				scheduleDeallocations(); // execute outside of lock, so very big pools won't hog CPU
    			}
    			SleepUtil.sleep(isShuttingDown() ? 0 : deallocatedAnObject ? 50 : 10);
    		}
    
    		private void deallocate(final PoolableObject<T> invalidatedObject) {
    			allocator.deallocate(invalidatedObject.getAllocatedObject());  // 2- exception bubbles up
    			invalidatedObject.setCurrentPoolStatus(PoolableObject.PoolStatus.DEALLOCATED);
    			invalidatedObject.dereferenceObject();
    		}
    ...
    
    
    	@Override
    	public void deallocate(Transport transport) {
    		LOGGER.trace("closing transport...");
    		try {
    			transport.close();
    		} catch (MessagingException e) {
                             // 1- exception here due to transport connection already closed by the server (the 10 second timeout on server side kills it)
    			throw new TransportHandlingException("error closing transport connection", e); 
    		}
    	}
    

    Here is the exception that kills it:

    09:17:10.776 [pool-1-thread-1] TRACE o.s.s.TransportAllocator - closing transport...
    Exception in thread "pool-1-thread-1" org.simplejavamail.smtpconnectionpool.TransportHandlingException: error closing transport connection
    	at org.simplejavamail.smtpconnectionpool.TransportAllocator.deallocate(TransportAllocator.java:62)
    	at org.simplejavamail.smtpconnectionpool.TransportAllocator.deallocate(TransportAllocator.java:30)
    	at org.bbottema.genericobjectpool.GenericObjectPool$AutoAllocatorDeallocator.deallocate(GenericObjectPool.java:283)
    	at org.bbottema.genericobjectpool.GenericObjectPool$AutoAllocatorDeallocator.allocatedCorePoolAndDeallocateOneOrPlanDeallocations(GenericObjectPool.java:270)
    	at org.bbottema.genericobjectpool.GenericObjectPool$AutoAllocatorDeallocator.run(GenericObjectPool.java:256)
    	at java.lang.Thread.run(Thread.java:748)
    Caused by: javax.mail.MessagingException: Can't send command to SMTP host;
      nested exception is:
    	java.net.SocketException: Connection or outbound has closed
    	at com.sun.mail.smtp.SMTPTransport.sendCommand(SMTPTransport.java:2415)
    	at com.sun.mail.smtp.SMTPTransport.sendCommand(SMTPTransport.java:2402)
    	at com.sun.mail.smtp.SMTPTransport.close(SMTPTransport.java:1409)
    	at org.simplejavamail.smtpconnectionpool.TransportAllocator.deallocate(TransportAllocator.java:60)
    	... 5 more
    Caused by: java.net.SocketException: Connection or outbound has closed
    	at sun.security.ssl.SSLSocketImpl$AppOutputStream.write(SSLSocketImpl.java:1110)
    	at com.sun.mail.util.TraceOutputStream.write(TraceOutputStream.java:140)
    	at java.io.BufferedOutputStream.flushBuffer(BufferedOutputStream.java:82)
    	at java.io.BufferedOutputStream.flush(BufferedOutputStream.java:140)
    	at com.sun.mail.smtp.SMTPTransport.sendCommand(SMTPTransport.java:2413)
    	... 8 more
    

    Past that point, the accumulation occurs at a rate equal to the number of core sender threads, since each of them will encounter no connection and will attempt to create a new one, which will succeed but never get cleaned up afterwards.

    You can repro this by just throwing that exception in that last function yourself, and see how the system behaves past that point.

    A few thread dumps show some progression:
    Startup time when pool-1-thread-1 is bootstrapping the pool.
    image

    Regular functioning of the pool-1-thread-1 sleeping waiting to deallocate while sender threads are sending:
    image

    After that thread dies once the exception is hit:
    image

  6. added this to the 7.1.1 milestone on Mar 27, 2022
  7. bbottema commented on Mar 27, 2022

    @bbottema
    Owner

    Excellent analysis! You might very well pin pointed the problem. I've already updated and released the up stream libraries (generic-object-pool, clustered-object-pool and smtp-connection-pool) and a new version of Simple Java Mail 7.1.1.
    Unfortunately, it's a pain to release this for the 6.x.x series. I hope you can switch to 7.1.1. Otherwise you might wanna try pinning the generic-object-pool dependency to version 2.0.1.

    Give it a go! I'll close this until the problem pops up again.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions