Java-Make functions asynchronous

So there must be a lot of threads running related to this topic over the internet, and is probably something that i must have read in basic Java class, it caught my attention only when i had to increase the performance of one of my codes.

I wrote a function which was doing two things in sequence :  model saving, email sending. The code was working fine but was taking like 6 seconds on an average to execute which is  a lot. I was then told to pass some functionalities of this function into another function and call the second created function asynchronously . Following is a high level of what was done :

Earlier :

Lets say a controller C calls this function A.

Class A {

function A () {

/*code for model saving*/

/*code for email sending*/



Now :

Class A {

function Aa () {

/*code for model saving*/

B instanceb=new B();

final JaloSession s = JaloSession.getCurrentSession();
final Tenant c= Registry.getCurrentTenant();




Class B {


function Bb(JaloSession session, Tenant currentTenant) {

/*code for email sending*/



Things to be noted in the above example :

  1. Function you need to make async must have the annotation “@Async”
  2. Function that you have made async must always be in different class from where it is being called, otherwise it will share the same session as the function’s from which it is called, and the whole purpose of making function async will go away.

This done, we are good to go with function making async.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s