java - Threads in spring: synchronized or @Scope("proptery") performance -
i have 2 spring beans. jmshandler
receives message
. processed , handed on mailhandler
sends mail. i've seen messages arrive @ jmshandler
in exact same time. when entering sendmail
method 1 of both isn't processed (no mail sent). expect that's threading issue.
i've got 2 possiblities handle issue:
a) set sendmail
method synchronized. means next execution stopped until first processed.
public class jmshandler { @autowired private mailhandler mailer; public void handlemessage(message msg) { mailer.sendmail(msg.getpayload().tostring()); } } @component public class mailhandlerimpl implements mailhandler { @override public synchronized void sendmail(string message) { // fancy stuff... // mail message. } }
b) define mailhandler scope "prototype" , using lookup applicationcontext.
public class jmshandler { @autowired private applicationcontext ctx; public void handlemessage(message msg) { mailhandler mailer = ctx.getbean(mailhandler.class) mailer.sendmail(msg.getpayload().tostring()); } } @component @scope("prototype") public class mailhandlerimpl implements mailhandler { @override public void sendmail(string message) { // fancy stuff... // mail message. } }
i think both ways ok. in terms of performance there issue? when using synchronized stop execution of next process , wait until first finished. second create new instance of mailhandlerimpl
when message has send (and of course autowire other things not shown here). or there third alternative?
the way spot performance issue metrics application behaviour. should see metrics , better use timer
can see how many message has been handled , how fast processed. it's awesome.
if mail handler capable of sending email in moment, make sure have 1 consumer. no need use synchronized
. if prefer concurrent process/ multi consumer, preferred, create mail handler each thread. leverage reactor ease parallel processing (use thread pool executor in event bus) , commons pool hold mail handler instances. thread pool executor size , mail handler pool size should equal. or, can use email service such mailgun ease concurrent email sending.
Comments
Post a Comment