Awesome Spring – Superlike @Cacheable @Async and @Scheduled

3 minute read

How many times in last 10 years I have to write code to cache things locally or in distributed cache? How many times did I write code to make heavy-lifting Java methods asynchronous?

Probably numerous! Each time with different style for different product!

 

In years such a boilerplate code becomes just that- a boilerplate PAIN. You know what to write how to write as it has long outlived the evolution cycle.  (Remember another Singleton code that you might still write every time? Still? )

Cometh the Spring. And what you need to do to make a method call asynchronous? Just tag it with an annotation @Async. That’s it. Yeah, you read it right- that’s it! That IS F*KNG awesome stuff. No boilerplate needed, and that’s how it should have been for long!

This gets the basic stuff ready in seconds and gets rid of writing the Executors, Threads and what now.

Here are few more cases of similar awesomeness I love. Just because they let me focus and get rid of boilerplate.

1. @Async – Asynchronous Processing using underlying ExecutorService

What would you do if you want to make a call to a method Asynchronous? Earlier, you would use an ExecutorService and pass an instance of thread and would end-up creating a small-little framework of your own.

Needed no more. You can simply configure the executor service in Spring application context XML and then use @Async annotation directly on a method to make that method call asynchronous.

Add following to application-context.xml:

<task:executor id="executor" pool-size="10"/>

And then use @Async annotation on the method:

@Async
public void doSomeHeavyLifting(String blah){
 liftingNow(); //Some kool heavy work
}

More on Async can be found in Spring Documentation here.

2. @Cacheable – A Cache abstraction provided by Spring

You almost in all live projects would have the need to cache some data in-memory; some part of which on local JVM while other on a cache layer like EhCache.

Spring now ships with this amazing Cache feature where you can abstract entire Caching easily and plug it with application super-fast. For example, if you want to cache some objects, say products from an ecommerce website, in a local Hashmap cache  (used only for simplicity sake. don’t dare to cache our entire catalog to Hashmaps!). You just need to configure the cache in context XML and then mark the method with annotation @Cacheable.

Add this to appContext:

<bean id="cacheManager" class="org.springframework.cache.support.SimpleCacheManager">
	<property name="caches">
	<set>
		<bean class="org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean" p:name="products"/>
	</set>
	</property>
</bean>

Now just use Cacheable annotation with the cache name “products”. Remember the cache name is important when dealing with keys and eviction.

@Cacheable(value="products", key="#productCode")
public Product getProductByCode(String productCode) {
 Product product = getFromSomewhere(code);
 return product;
}

The above  method returns the Product object and this value is Cached. Subsequent invocation of this method would return the cached value. Do note that “key” provided in Cacheable annotation plays an important role. If we do not use key in the above example, subsequent invocation of this method would return the same value irrespective of the parameter productCode. So choose key wisely, as always :).

Here is detailed documentation on Spring Cache.

 

3. @Scheduled – Task Scheduler

Even elementary task scheduling requires good amount of code to be written if not using another framework like Quartz. Which is overwork for non-critical scheduling stuff. Fortunately, Spring now comes with Task Scheduler support.

Add scheduler configuration in app context:

<task:scheduler id="appScheduler" pool-size="5"/>

And just add @Scheduled annotation on the method that you want to be invoked periodically:

@Scheduled(fixedDelay=5000)
public void purge() {
    // purge periodically
}

The above method would be executed every 5 seconds. The annotation takes parameter, fixedDelay, fixedRate or cron. cron can be used to provide more sophisticated scheduling.

 

I just loved these annotation in my project and were really helpful in speeding-up development. Helped you similarly? Put your views in comments section below.

 

And yes, one more time – Spring is Awesome!!!

 

Tags:

Categories:

Updated:

Leave a Comment