Alastair
Alastair

Reputation: 470

Is it acceptable to leave the javamail session Transport open?

My application needs to send emails on an ad hoc basis. I'm using javamail's getDefaultSession and getTransport to send the message, and it's all working as expected.

However I've noticed that the send can take a long time - up to seven seconds per send. If I break the steps down, like this:

Transport transport = session.getTransport("smtp");
transport.connect();
transport.sendMessage( msg, addresses )
transport.close();

...I can see that it's the connect() call that takes almost all of the time, each time.

All of the examples I've found do this - get a transport, connect, send, disconnect. But of course they're all single-shot examples, or sending large batches of emails in a single call.

I was thinking I could just leave the connection open, like this:

Transport transport = session.getTransport("smtp");
if (!transport.isConnected())
    transport.connect();
transport.sendMessage( msg, addresses )

(There's a variation on that, here: java mail keeping Transport object connected).

I'll have to close it eventually, in a shutdown hook of some kind. And I might have to have a fallback (if the connection has been lost but the transport doesn't realise). But is there any reason not to just leave it open like this during the application lifetime?

Thanks, Alastair

Upvotes: 19

Views: 13301

Answers (2)

Yuriy Nakonechnyy
Yuriy Nakonechnyy

Reputation: 3842

As per @Bill Shannon's (author of JavaMail) answer here: Threadsafety in Javamail

Since a Transport represents a connection to a mail server, and only a single thread can use the connection at a time, a Transport will synchronize access from multiple threads to maintain thread safety, but you'll really only want to use it from a single thread.

So if you plan to use single Transport instance from multiple threads (which is usually the case nowadays), it's actually quite bad idea from performance point of view. You'll probably better off developing some sort of pool of Transport instances using ThreadLocal.

Upvotes: 5

Tomas Narros
Tomas Narros

Reputation: 13468

I don't really see any problem in keeping a single SMTP connection open, and the use of Transport Object is recommended for connection reuse (see the JavaMail tutorial).

Additionally, I would recommend you to keep just one smpt connection (through Transport) open at your application, keeping it at a single manager instance (i.e using a singleton pattern), avoiding the eventual cost of keeping a different connection open for every component which needs send a message.

Upvotes: 8

Related Questions