Skip to content

Commit 91b427f

Browse files
committed
Merge remote-tracking branch 'upstream/master' into 204-fix-race-condition-improve-threading
2 parents 9bc467f + 4cffe67 commit 91b427f

File tree

1 file changed

+23
-9
lines changed

1 file changed

+23
-9
lines changed

src/main/java/org/simplejavamail/mailer/internal/mailsender/MailSender.java

+23-9
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,8 @@
2525
import java.util.concurrent.ExecutorService;
2626
import java.util.concurrent.Executors;
2727
import java.util.concurrent.Phaser;
28+
import java.util.concurrent.ThreadFactory;
29+
import java.util.concurrent.atomic.AtomicInteger;
2830

2931
import static java.lang.String.format;
3032
import static org.simplejavamail.converter.EmailConverter.mimeMessageToEML;
@@ -192,14 +194,31 @@ the proxy bridge server (or connection pool in async mode) while a non-async ema
192194
smtpRequestsPhaser.register();
193195
if (async) {
194196
// start up thread pool if necessary
195-
if (executor == null || executor.isTerminated()) {
196-
executor = Executors.newFixedThreadPool(operationalConfig.getThreadPoolSize());
197+
if (executor == null) {
198+
executor = Executors.newFixedThreadPool(operationalConfig.getThreadPoolSize(), new ThreadFactory() {
199+
final AtomicInteger threadCounter = new AtomicInteger(0);
200+
@Override
201+
public Thread newThread(Runnable r) {
202+
Thread thread = new Thread(r, "Simple Java Mail async mail sender #" + threadCounter.getAndIncrement());
203+
if (!thread.isDaemon()) {
204+
thread.setDaemon(true);
205+
}
206+
if (thread.getPriority() != Thread.NORM_PRIORITY) {
207+
thread.setPriority(Thread.NORM_PRIORITY);
208+
}
209+
return thread;
210+
}
211+
});
197212
}
198213
configureSessionWithTimeout(session, operationalConfig.getSessionTimeout());
199214
executor.execute(new Runnable() {
200215
@Override
201216
public void run() {
202-
sendMailClosure(session, email);
217+
try {
218+
sendMailClosure(session, email);
219+
} catch (Exception e) {
220+
LOGGER.error("Failed to send email", e);
221+
}
203222
}
204223

205224
@Override
@@ -300,7 +319,7 @@ private void configureBounceToAddress(final Session session, final Email email)
300319
}
301320

302321
/**
303-
* We need to keep a count of running threads in case a proxyserver is running or a connection pool needs to be shut down.
322+
* We need to keep a count of running threads in case a proxyserver is running
304323
*/
305324
private synchronized void checkShutDownRunningProcesses() {
306325
smtpRequestsPhaser.arriveAndDeregister();
@@ -313,11 +332,6 @@ private synchronized void checkShutDownRunningProcesses() {
313332
LOGGER.trace("stopping proxy bridge...");
314333
proxyServer.stop();
315334
}
316-
// shutdown the threadpool, or else the Mailer will keep any JVM alive forever
317-
// executor is only available in async mode
318-
if (executor != null) {
319-
executor.shutdown();
320-
}
321335
}
322336
}
323337

0 commit comments

Comments
 (0)