问题描述
我有一种方法可用于发送电子邮件。我想锁定这个方法,所以每次只有一个线程可以接受它,并且其余的池同时存在。我应该同步方法还是在我的服务层使用spring @transactional PROPAGATION_REQUIRED?
I have a method that will be used to send out email. i want to lock this method so only one thread can accses it per time and the rest pool up concurrently. should i synchronized the method or use spring @transactional PROPAGATION_REQUIRED ?
//each time use new thread to send out email
public void sendThroughSMTP(List<String> emails,String subject,String content){
//each time will open and sent through port 25. dont u think this will caused too many threads spawned?
BlastEmailThread blastEmailThread = new BlastEmailThread(emails,subject,content);
blastEmailThread.start();
}
推荐答案
为什么不通过不使用任何实例级别的东西使方法线程安全?
Why not make the method thread-safe by not using any instance level things?
但是,我不知道Spring的交易管理是如何适合的。我的意思是Spring提供了很少的事务管理器,即 DataSourceTransactionManager
, JtaTransactionManager
, HibernateTransactionManager
这一切都与数据库持久性有关。您将为此电子邮件发送什么配置?
However, I don't see how Spring's Transaction Management fits here. I mean Spring provides few transaction managers, i.e. DataSourceTransactionManager
, JtaTransactionManager
, HibernateTransactionManager
all this is about database persistence. What will you configure for this email send out?
我相信,首先您应该首先向我们展示您为什么担心线程安全问题。很可能您想向我们展示一些相关的代码片段或其他内容。然后我们可能会建议你。
I believe, first you should show us why you worry about the thread-safety in the first place. Most probably you would like to show us some relevant code snippet or something. Then we might be able to suggest you something.
[附录]
当您为该方法的每次调用生成一个线程而不使用该状态中的任何内容时,那么为什么要使方法 synchronized
。使方法同步不会以任何方式限制线程数。在启动新线程之前,由于同步,前一个线程可能已经完成了工作。产生线程的过程可能会变慢。
When you are spawning a thread for every call to that method and not using anything from the state, then why you want to make the method synchronized
. Making the method synchronized will not limit the number of threads in any way. There might be chance that before starting a new thread, previous thread might have finished the work, because of synchronization. The process of spawning a thread might go slower.
但是,你应该继续这样做,直到你发现有很多线程正在运行并且你的内存不足。如果你真的想在时间之前解决这个问题,那么你应该选择一些阻塞机制,比如。
However, you should go with this until you find out that there are really many threads running and you are going out of memory. And if you really want to tackle that before time, then you should choose some blocking mechanism, something like Semaphore.
这篇关于同步方法还是使用spring @transactional?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!