You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Hi! This is more of a question rather than an issue.
I'm working on an implementation that has to send many emails using one and the same SMTP server. I saw that async sending is already supported which is pretty cool! However, I was looking for a way to send many emails synchronously over an already established TCP connection.
Browsing the MailSender code I stumbled on this part. I think this opens a new connection for each email, right? Does it make sense to improve this, so that it reuses the transport/session to send several messages synchronously?
Hi @petarov, it could be an improvement, but I'm unaware of any performance issues with creating new connections for emails. Do you have experience with sending emails in bulk such that reusing a connection shows better results? Or is there another reason you wish to reuse a connection?
Thanks for the feedback @bbottema! I'd like to reuse the connection so that that same underlying tcp socket gets used for sending bulk (hundreds to thousands of emails) of data. I'm generally trying to squeeze as much performance as possible for a product I'm working on.
That being said, I don't have any data to compare the performance at the moment, but I'll try to prepare some and come back to you with numbers for a better overview.
Thanks, it would be very helpful to have some more data. Generally speaking as a rule of thumb I'm very cautious of premature optimization, since that makes the code more complex often without really needing it. But if a real case can be made I'm all for it.
Ok, here are a bunch of, let's call them naïve, tests using SimpleJavaMail and just plain JavaMail with Transport.sendMessage(). I've used FakeSMTP as an SMTP server to perform the tests. Test email size = 15Kb.
It can be observed in the SMTP protocol handshake that the JavaMail+sendMessage variant does not close the connection, but rather keeps sending emails after EHLO was initially sent. The results from my tests are below. The client code's running on a macOS machine and the SMTP server on a remote Linux server.
The elapsed time results as mean values are irrelevant, but the difference does seem to be around 2x in favour of JavaMail+sendMessage.
Method
Emails Count
Elapsed Time
SimpleJavaMail
100
40,71 seconds
JavaMail+sendMessage
100
21,11 seconds
SimpleJavaMail
1000
404.71 seconds (6m 45s)
JavaMail+sendMessage
1000
198.70 seconds (3m 18s)
SimpleJavaMail
10,000
3921,03 seconds (1h 5m 22s)
JavaMail+sendMessage
10,000
1954,81 seconds (32m 35s)
Of course, I might have missed something, so here's the repo, if you'd like to take a look. (Warning! Code's messy.)
And finally, I actually think that 2x is not that much of an issue for my use case (~500 max), so this issue could be closed. I can live with SimpleJavaMail working as it is at the moment. 😉
Can you please add a third approach of JavaMail sendMessage without reusing the connection? I'm curious to know how much overhead Simple Java Mail adds.
Variant 5 - transportInstance.sendMessage(). Same as JavaMail+sendMessage in my tests above. Transport instance is created once and it's used for each email being sent.
if (!transport.isConnected())
transport.connect();
transport.sendMessage(msg, msg.getAllRecipients());
Results
#
Method
Emails Count
Elapsed Time
1
SimpleJavaMail
100
38,64 seconds
2
SimpleJavaMail+10 Threads
100
0,14 seconds
3
Transport.send()
100
38,16 seconds
4
Transport+getInstance()+connect()+sendMessage()
100
38,79 seconds
5
transportInstance.sendMessage()
100
19,22 seconds
No doubt, SimpleJavaMail + threads is the fastest variant, if threading is desired. 😎
Last edit, maybe it's worth adding that Variant 5 should be used with caution in multi-threaded scenarios as stated in this stackoverflow comment.
In conclusion, Simple Java Mail performance is pretty good in parallel mode, but can be improved even further roughly increasing performance by a factor of two when reusing Transport connections from a pool.
Interesting though that establishing a connection to the smtp server takes about the same time as actually sending an email to it!
I'll leave this open after all as a low-priority enhancement. Thanks again!
Unless this is a bug, this can only occur if the pool was shut down and then reused. On shut down, the connection pools are discarded, but the cluster key remains. If you then try to reuse the cluster key, this exception is thrown.
Is it possible, you are shutting down the connection pool on this line, before the threads are done sending? That would explain the 0,12 seconds ;)
Yeah, that was a bummer. The test did not wait on the AsyncResponse futures to complete. It seems my older tests were also compromised by this. I totally overlooked it.
It looks much more realistic now at 4,47 sec. I've updated the table above. 😉
Still, I'm unsure when/how to call mailer.shutdownConnectionPool(). If I invoke mailer.shutdownConnectionPool().get() when all messages get sent, it just seems to block indefinitely. Any advice on that?
Seeing your code, I can imagine two methods for shutting down:
The current one that waits for shutdown or times out with exception
A new one that waits for shutdown or forces a shutdown after a timeout
Regarding your question on how to use the current one: if your threads are done, it should definitely not block indefinitely. That would be a bug.
One possibility is that, while sending an email in a thread, if it fails then the claimed Transport is not released back into the pool. In this scenario the pool blocks indefinitely because it waits for all resources to free up. Did you verify all mails sent without issue?
Though that might also be considered a bug if a transport is not released if the email was met with an exception (although releasing it back to the pool might mean the pool is now poisoned with a broken resource). Hmm, food for thought.
Yep, they are all being sent successfully. I did a simple 10 emails tests. All received and no exception was reported by AsyncResponse.onException(). I could see all 10 at the SMTP server side as well.
Interestingly enough, if I just create a new mailer and invoke mailer.shutdownConnectionPool().get() without sending any Emails, it also blocks indefinitely. 🤔
Yep it's a bug. The combined Futures of all pools being shutdown are aggregated into a FutureTask which itself is never run (the pools do shutdown, but the future task doesn't perform the wait closure) so it never completes and hence .get() blocks indefinitely. Whoops.
Actually were are a bunch of issues where executor services were not shut down properly, the aggregate pools shutdown future task not executing (and implemented wrong).
@petarov With that out of the way, could you please add a test with both multiple threads and a connection pool? The best would be to run a warmup cycle first and then perform all tests at once so they are guaranteed to run under same parameters.
Also if you would post the system details (cpu, memory etc.) of both the client and server system that would be a great help. This would give a more complete frame of reference and I'll include it on the website as a rough reference performance (awesome!). If you're ok with having this data published that is.
Here's the input you requested, but I'm not sure if this is something to put on the website. I expect the results will definitely very when using a real SMTP server. It's your call. 😉
Test Parameters
simplejavamail 6.0.2
javax.mail 1.6.2
100 emails sent to a remote SMTP server with average ping ~50 ms.
Client - macOS Catalina, 8 CPU, 16 GB RAM, AdoptOpenJDK 11. Java VM was warmed up.
Server - CentOS Linux, 6 CPU, 12 GB RAM, OpenJDK 1.8, FakeSMTP as server*
Results
Test
Emails Count
# 1
# 2
# 3
Average Elapsed Time
ThreadPoolSize=10 + CPool MaxSize=4
100
4.41
4.56
4.71
4.56 sec.
ThreadPoolSize=10 + CPool MaxSize=1
100
14.86
14.61
14.58
14.68 sec.
ThreadPoolSize=0 + CPool MaxSize=4
100
16.64
16.50
16.91
16.68 sec.
JavaMail Transport
100
19.60
18.82
19.93
19.45 sec.
Both threaded and connection pool tests were done with the default values in the MailerRegularBuilderImpl builder. No customizations of the thread pool or connection pool sizes.
FakeSMTP ran in memory mode, no mails were saved on disk, using java -jar fakeSMTP-2.0.jar -m -s -b -p <port>
Thanks a lot for your effort! Maybe I'm misunderstanding though, because I still miss a test with both multiple threads and a connection pool (as a combo).
Additionally, I don't suppose it's easy for you to set up another server (or two) to run as a cluster? I wonder if we can get those 100 emails down to a single second 😏
Just did an update of my comment above. TBH, I'm a bit unsure of the exact specifics of how the threads and connection pools are working together, but the performance does seem to improve as I increase the number of threads and connection pool max size. So, it is more or less what I would have expected.
A cluster run would be a challenge. Can't promise anything, but perhaps if time permits.
Activity
bbottema commentedon Mar 29, 2019
Hi @petarov, it could be an improvement, but I'm unaware of any performance issues with creating new connections for emails. Do you have experience with sending emails in bulk such that reusing a connection shows better results? Or is there another reason you wish to reuse a connection?
petarov commentedon Mar 31, 2019
Thanks for the feedback @bbottema! I'd like to reuse the connection so that that same underlying tcp socket gets used for sending bulk (hundreds to thousands of emails) of data. I'm generally trying to squeeze as much performance as possible for a product I'm working on.
That being said, I don't have any data to compare the performance at the moment, but I'll try to prepare some and come back to you with numbers for a better overview.
bbottema commentedon Apr 1, 2019
Thanks, it would be very helpful to have some more data. Generally speaking as a rule of thumb I'm very cautious of premature optimization, since that makes the code more complex often without really needing it. But if a real case can be made I'm all for it.
petarov commentedon Apr 5, 2019
Ok, here are a bunch of, let's call them naïve, tests using SimpleJavaMail and just plain JavaMail with Transport.sendMessage(). I've used FakeSMTP as an SMTP server to perform the tests. Test email size = 15Kb.
It can be observed in the SMTP protocol handshake that the
JavaMail+sendMessagevariant does not close the connection, but rather keeps sending emails afterEHLOwas initially sent. The results from my tests are below. The client code's running on a macOS machine and the SMTP server on a remote Linux server.The elapsed time results as mean values are irrelevant, but the difference does seem to be around 2x in favour of
JavaMail+sendMessage.Of course, I might have missed something, so here's the repo, if you'd like to take a look. (Warning! Code's messy.)
And finally, I actually think that 2x is not that much of an issue for my use case (~500 max), so this issue could be closed. I can live with SimpleJavaMail working as it is at the moment. 😉
bbottema commentedon Apr 5, 2019
Can you please add a third approach of JavaMail sendMessage without reusing the connection? I'm curious to know how much overhead Simple Java Mail adds.
petarov commentedon Apr 6, 2019
Sure, so I tested 5 variants.
Variant 1 - SimpleJavaMail. (Default Mailer, no threading parameters.)
Variant 2 - SimpleJavaMail with 10 threads. Async send.
Variant 3 - Transport.send()
Variant 4 - Transport+getInstance()+connect()+sendMessage().
Variant 5 - transportInstance.sendMessage(). Same as JavaMail+sendMessage in my tests above. Transport instance is created once and it's used for each email being sent.
Results
No doubt, SimpleJavaMail + threads is the fastest variant, if threading is desired. 😎
Last edit, maybe it's worth adding that Variant 5 should be used with caution in multi-threaded scenarios as stated in this stackoverflow comment.
bbottema commentedon Apr 6, 2019
Excellent work, thank you!
In conclusion, Simple Java Mail performance is pretty good in parallel mode, but can be improved even further roughly increasing performance by a factor of two when reusing Transport connections from a pool.
Interesting though that establishing a connection to the smtp server takes about the same time as actually sending an email to it!
I'll leave this open after all as a low-priority enhancement. Thanks again!
27 remaining items
bbottema commentedon Jan 26, 2020
Unless this is a bug, this can only occur if the pool was shut down and then reused. On shut down, the connection pools are discarded, but the cluster key remains. If you then try to reuse the cluster key, this exception is thrown.
Is it possible, you are shutting down the connection pool on this line, before the threads are done sending? That would explain the 0,12 seconds ;)
petarov commentedon Jan 26, 2020
Yeah, that was a bummer. The test did not wait on the
AsyncResponsefutures to complete. It seems my older tests were also compromised by this. I totally overlooked it.It looks much more realistic now at
4,47 sec.I've updated the table above. 😉Still, I'm unsure when/how to call
mailer.shutdownConnectionPool(). If I invokemailer.shutdownConnectionPool().get()when all messages get sent, it just seems to block indefinitely. Any advice on that?bbottema commentedon Jan 27, 2020
Seeing your code, I can imagine two methods for shutting down:
Regarding your question on how to use the current one: if your threads are done, it should definitely not block indefinitely. That would be a bug.
One possibility is that, while sending an email in a thread, if it fails then the claimed Transport is not released back into the pool. In this scenario the pool blocks indefinitely because it waits for all resources to free up. Did you verify all mails sent without issue?
Though that might also be considered a bug if a transport is not released if the email was met with an exception (although releasing it back to the pool might mean the pool is now poisoned with a broken resource). Hmm, food for thought.
petarov commentedon Jan 28, 2020
Yep, they are all being sent successfully. I did a simple 10 emails tests. All received and no exception was reported by
AsyncResponse.onException(). I could see all 10 at the SMTP server side as well.Interestingly enough, if I just create a new mailer and invoke
mailer.shutdownConnectionPool().get()without sending any Emails, it also blocks indefinitely. 🤔bbottema commentedon Jan 30, 2020
Yep it's a bug. The combined Futures of all pools being shutdown are aggregated into a FutureTask which itself is never run (the pools do shutdown, but the future task doesn't perform the wait closure) so it never completes and hence
.get()blocks indefinitely. Whoops.bbottema commentedon Jan 31, 2020
Actually were are a bunch of issues where executor services were not shut down properly, the aggregate pools shutdown future task not executing (and implemented wrong).
I've fixed all these issues under #246.
bbottema commentedon Feb 1, 2020
6.0.2 released, all shutting down issues should be gone now!
bbottema commentedon Feb 1, 2020
@petarov With that out of the way, could you please add a test with both multiple threads and a connection pool? The best would be to run a warmup cycle first and then perform all tests at once so they are guaranteed to run under same parameters.
Also if you would post the system details (cpu, memory etc.) of both the client and server system that would be a great help. This would give a more complete frame of reference and I'll include it on the website as a rough reference performance (awesome!). If you're ok with having this data published that is.
petarov commentedon Feb 3, 2020
Ok, it all looks good in
6.0.2so far.Here's the input you requested, but I'm not sure if this is something to put on the website. I expect the results will definitely very when using a real SMTP server. It's your call. 😉
Test Parameters
6.0.21.6.2~50 ms.macOS Catalina, 8 CPU, 16 GB RAM, AdoptOpenJDK 11. Java VM was warmed up.CentOS Linux, 6 CPU, 12 GB RAM, OpenJDK 1.8, FakeSMTP as server*Results
Both threaded and connection pool tests were done with the default values in the
MailerRegularBuilderImplbuilder. No customizations of the thread pool or connection pool sizes.FakeSMTP ran in memory mode, no mails were saved on disk, using
java -jar fakeSMTP-2.0.jar -m -s -b -p <port>bbottema commentedon Feb 3, 2020
Thanks a lot for your effort! Maybe I'm misunderstanding though, because I still miss a test with both multiple threads and a connection pool (as a combo).
Additionally, I don't suppose it's easy for you to set up another server (or two) to run as a cluster? I wonder if we can get those 100 emails down to a single second 😏
petarov commentedon Feb 17, 2020
Just did an update of my comment above. TBH, I'm a bit unsure of the exact specifics of how the threads and connection pools are working together, but the performance does seem to improve as I increase the number of threads and connection pool max size. So, it is more or less what I would have expected.
A cluster run would be a challenge. Can't promise anything, but perhaps if time permits.
bbottema commentedon Feb 17, 2020
Yeah, don't feel pressured at all, you did so much already.
bbottema commentedon May 3, 2020
So we ran into this bug, which I think makes all your tests invalid? (crap)