Spring Task Execution API to speeding up asynchronous calls

Is your app running slow… how about making some part of your code asynchronous. Its really easy and 5 minutes task to make it so using Spring Task Execution API. Why to bother about creating your own thread objects, implementing interfaces.

Try this out, a 5 minutes recipe…..

Spring 3 provides a Task Execution API that allows us to wrap beans with a proxy that calls @Async annotated methods asynchronously. The easiest approach would be simply to annotate your desired service method with @Async, however you need to limit the scope of such method on the forked thread, which means no db operations,  no user interaction, etc can go inside such method.

HOW TO CONFIGURE YOUR APP FOR ASYNCHRONOUS TASKS

Just adding the @Async annotation isn’t enough. We need to do little configuration in applicationContext.xml and all done…

Step 1: Add Task namespace and Task namespace schema location

<beans xmlns="http://www.springframework.org/schema/beans"</span>
xmlns:task="http://www.springframework.org/schema/task" xmlns:p="http://www.springframework.org/schema/p"
.......
 xmlns:jbpm="http://drools.org/schema/drools-spring" xmlns:cache="http://www.springframework.org/schema/cache"
 xsi:schemaLocation="http://www.springframework.org/schema/jee
.....
 http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd">

Step2: Activate @Async and Task executor for asynchronous calls

<task:annotation-driven />

<task:executor id="ekramExecutor" pool-size="5-15" queue-capacity="50" keep-alive="500" />

Details of task:executor

Attribute Description
id Bean ID
pool-size Number of threads in the pool. Either a single integer or a range such as “5-15″.
queue-capacity Task queue capacity.
keep-alive time in seconds for threads in excess of the core pool size.
rejection-policy Policy when threads are rejected (queue exhausted and pool size at maximum). Options are ABORT (default), CALLER_RUNS, DISCARD and DISCARD_OLDEST.

For complete project, check out https://github.com/ekramalikazi/spring-async-cache

Try this out, improve end-user response time and shine… :) Enjoy…

About these ads

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s

Follow

Get every new post delivered to your Inbox.