springmultithreadingmail-sender

Is JavaMailSenderImpl of spring thread-safe?


I am using JavaMailSenderImpl from spring to send emails in my web application. I have created only one instance of this (Actually it is used by another object which is created using spring beans and is a singleton).

So the question is, Is JavaMailSenderImpl thread-safe? In my app, when multiple threads are using the mailSender simultaneously, will it lead to any race conditions?


Solution

  • Yes the JavaMailSenderImpl is thread safe once it is constructed.

    Take a look at the doSend method which does the actual work. It contains only method local variables (so each calling thread/stack has its own instance). (The same applies to the send method which add some functionality).

    The methods like getSession are synchronized so only a single thread can have access to that method.

    The biggest thing that makes it thread safe is the fact that there is (almost) no mutable shared state and the single mutable shared state (the Session) that there is is synchronized.

    Next to that have been using it for over 12 years in production systems in a singleton fashion and never had any issues with concurrency. And yes we used it in highly concurrent applications. (And it is also the way other framework components like Spring Batch and Spring Integration use the JavaMailSender API).