spring - Thread safety with @Scheduled and @Async, Java -


i took code:

private queue<object> myqueue = new concurrentlinkedqueue();  public enqueue(object obj) {   myqueue.add(obj); }  @scheduled(fixedrate=1000) public void publish() {   final list objstopublish = lists.newarraylist();   final int listsize = myqueue.size();   (int = 0; < listsize; i++) {      objstopublish.add(myqueue.poll());   }    expensivewriteoperation(objstopublish); } 

however, it's problem if publish() takes away control during other operations running in software, tried make expensive call asynchronous, so:

private queue<object> myqueue = new concurrentlinkedqueue();  public enqueue(object obj) {   myqueue.add(obj); }  @scheduled(fixedrate=1000) public void publish() {   final list objstopublish = lists.newarraylist();   final int listsize = myqueue.size();   (int = 0; < listsize; i++) {      objstopublish.add(myqueue.poll());   }    work(objstopublish); }  @async void work(list objstopublish) {   expensivewriteoperation(objstopublish); } 

i concerned 2 things.

1) code work, if enqueue called @ time, mid-work()?

2) passing data queue in right way?

in case work() method must public , must called outside class has publish() method. if spring, using dynamic proxies in case once call publish() elsewhere, @async annotation of work() method no longer @ play since inside proxied instance.

try this:

interface asyncinternalwrapper {     void work(list objstopublish); }   @service public class asyncinternalwrapperimpl implements asyncinternalwrapper {     @async     public void work(list objstopublish) {       expensivewriteoperation(objstopublish);     } } 

then

@autowired private asyncinternalwrapper wrapper;  @scheduled(fixedrate=1000) public void publish() {   ....    wrapper.work(objstopublish); } 

on side note, since scheduled process, not require user interaction. real benefit of making publish() call return quicker? may want think twice of benefit (if any) async operation provide , not over-engineer without argument.

regarding concerns, bear in mind publish() executed in own thread executor service, naturally doing "async" call. i'm guessing impetus using concurrent queue. happens @async spawning (or taking thread pool) thread in addition 1 executing publish()


Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

css - Make div keyboard-scrollable in jQuery Mobile? -

ruby on rails - Seeing duplicate requests handled with Unicorn -