0

i am trying to make a method async using @Async annotation provided by Spring 3.0

i have done following

inclued following in my module-context.xml

<task:executor id="initiateContactCreation" pool-size="2-10" queue-capacity="5"/>
<task:annotation-driven executor="initiateContactCreation" />

annotated method with @Async

@Async
    private void initiateContactCreation(String fromUserId, List<String> toUsers){
        logger.info("Inside Async method for contact creation");
        ContactDetails contactDetails = new ContactDetails();
        contactDetails.setUserId(fromUserId);
        contactDetails.setContactEmailIds(toUsers.toArray(new String[toUsers.size()]));
        this.contactsAndDirSvc.addContact(contactDetails);
        logger.info("Returning from Async method for contact creation");
    }

but i see that the method does not return control immediately.

my logger shows logs from initiateContactCreation then logs from addContact(PS. it is taking time executing this method and i do not want it to be executed synchronously) and then logs from the method from where i am calling initiateContactCreation

what am i doing wrong?

dev2d
  • 4,245
  • 3
  • 31
  • 54

2 Answers2

5

Since this method is private, I assume that you're calling this method from within this class using the 'this' reference. Spring cannot proxy calls which are made within class. the call has to come from outside of your class so that Spring can intercept and apply annotations and other proxying stuff that it does.

Praba
  • 1,373
  • 10
  • 30
  • will making my method public do the thing? – dev2d Apr 30 '14 at 18:22
  • Making it public and then also invoking it using `this` will not help. A better approach would be to move this method to a different service, (if possible, behind an interface) which would make it easier for Spring to proxy. – Praba Apr 30 '14 at 18:29
  • making it public is not working, now i need to try moving it into different class and invoke right? also i am not using this to call the method – dev2d Apr 30 '14 at 18:37
-1

prabugp's explanation is spot on, I don't have anything more to add to it.

I do have some links however that you should check regarding Spring AOP's pitfalls and how to get past them (also applies to your code).

1, 2, 3, 4

Community
  • 1
  • 1
geoand
  • 60,071
  • 24
  • 172
  • 190