We are using a mail-service in my web application (Jetty). The service object is injected using spring beans at run-time.
Now, the service is not thread-safe. How can we handle this? On reading through some of the posts here I found following options. Please let us know the pros & cons of the following.
Spring config:
<bean id="mailService" class="com.....MailService">
<property name="mailSender" ref="mailSender" />
<property name="registrationEmailMessage" ref="registrationEmail" />
...
</bean>
Java Bean
@Autowired
MailService mailService;
Synchronize methods inside mail service.
Synchronizing through blocking can slow down application, depends on execution time of synchronized block. If it's a singleton
bean, calls to MailService
will be executed sequentially. Even if it's a prototype
bean, it still can be called from different threads simultaneously and will lead to sequential execution.
Create new object everytime. If it doesn't consume significant time and resources, it's a good solution. Create new objects as local variable in methods, they will not be shared between threads.
ThreadLocal. Powerful concept, but has own problems:
Object pool. I root for this solution. Thread-safety in this case can be achieved by writing a new thread-safe optimized silgleton wrapper bean, which in this case will contain MailService
objects pool. Wrapper can be safely accessed from any thread and it redirects execution down to the pool. Here is an example.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.