May 18, 2010

Java Code Optimization: Tip # 1: How To Use Java Map .contains() and .get()

One very common mistake that I see in application code written in java is the way maps are accessed! Though it is very common, in my opinion I would say that this is an expensive mistake! Go ahead, get to know what the error literally is and correct the same if you come across one in future for that would help you to have an optimized code on the fly.

Let us say that we have a map! Let us create the map
Map<Integer,String> testMap = new HashMap<Integer, String>();

Here, while looping through the keyset of the above Hashmap, a java developer very often tries to do the following:

Un-Optimized Code:
<br />if(testMap.contains(1))<br />{<br />    String tempString = testMap.get(1);<br />    System.out.println(tempString);<br />}<br />

This is emphatically a stress to the memory and makes an un-optimized code. Here,
  • We check whether the map contains the key we are looking for.
  • Next, we try to get the value of the key if the key is present in the map
  • We access the map 2 times and if this is placed within a for loop, imagine the number of times we would be accessing the map

The above code can easily be replaced by:

Optimized Code:
<br />String tempString = testMap.get(1);<br />if( tempString == null)<br />{<br />    System.out.println(tempString);<br />}<br />

In the optimized code,
  • we are not checking whether the map contains the key we are looking for.
  • We are just trying to get the value for the key specified.
  • If the key exists in the map, we would have a valid value in the tempString.
  • Else, this would be null and hence we access the map just once for every check we do!

In my opinion, rather than accessing map.contains() and map.get() for every check, trying to get the value by using map.get() would render an optimized code
That was one optimization technique that I found was really utile! And hence thought of sharing the same with you all!

May 10, 2010

Spring Annotations: A Remarkable Reference

I was surfing the Internet and accidentally came across a nice reference for Spring. Since i work with more of Spring annotations, I really found it to be very cool!!! A reference card for Spring annotations is emphatically rare! It is quite useful too!! I thought it is a must have for a programmer who works in java and especially Spring based web application using annotations.

This thought forced me to share the same with you guys too! Here is a list of Core Spring Annotations, Spring MVC annotations, Aspect J and JMX annotations along with JSR 250 and Testing annotations too!! Go through this and have a good time! Keep me posted with your feedback as usual!

Reference Card for Spring Annotations


May 5, 2010

How To Use @Async in Spring Web Application?

I decided to give the @Async annotation a try! The recently added @Async annotation in the Spring Framework 3.0 seems to be an easy fit for applications that would require asynchrous calls to be invoked while the application is running or deployed! Here is a sample code that can help you with making your @Async annotation work with ease!
  1. As the first step, you have to incorporate the schema location detail and the xmlns detail for the task tag in Spring framework. The xmlns configuration details that you need to include is:
  2. The schema location configuration details that you need to include in your application context includes
  3. Next, make Spring container understand that you are going to invoke asynchrous tasks that are annotation driven. So, remember to add the following line in your applicationContext.xml file.

    <br /><task:annotation-driven><br />
  4. After this, check your configuration xml file to ensure that you have implemented the context scanning on the code package where you are going to define the asynchronous jobs that you expect to be run by the spring framework. Let us say, we have a package where we are going to have a class that would have all the methods annotated with @Async here and these would in turn be invoked by the scheduler. Then, ensure that you have this package as a part of the component scanning tag within the configuration xml file as follows:

    <br /><context:component-scan base-package=""><br />
  5. Now, we are almost complete with the changes in the configuration files. Next, let us go ahead with a class that would have methods annotated with @Async which are in turn the asynchronous tasks that would be invoked within our application. Remember, as discussed earlier, this class needs to be in package. Let us refer to this class as The code for this class would look something like:

    <br />package org.test.common.utils.Tasks;<br />import java.util.Date;<br />import org.springframework.scheduling.annotation.Async;<br />import org.springframework.transaction.annotation.Transactional;<br />import org.springframework.stereotype.Component;<br />@Component<br />public class MyScheduler implements Scheduler{<br />@Transactional(readOnly = false)<br />@Async<br />public void testTask() {<br />System.out.println("Starting to process the task at " + new Date()); <br />}<br />}<br />
  6. And that is it! You are done. The @Async tells the spring container that the method underneath is an asynchronous task that would be invoked within the application. You can call this method from any class using the snippet as given below:

    <br />@Autowired<br />private Scheduler s;<br /><br /> s.newTask();<br />
  7. Further, when you use @Async you can return parameters from those methods and that should be Future typed. Say Future etc! That is unbelievable. Even if you want to update the db, you can go ahead and get the current session and process this method within a transaction to make db updates on a periodical basis.
If you find the information pretty helpful, I would really be happy if you would keep me posted via the comments form displayed under this article! If you had wanted some other information related to the same topic, I would suggest you to drop a note to me using the comments form for that would help me in getting back to you with the details you are in need of!

May 4, 2010

How to Implement a Task Scheduler/ Job Scheduler in Spring Framework using Annotations?

I had a chance to analyze how the task scheduler works in Spring framework today!! The recent addition of the @Scheduled and @Async into Spring framework 3.0 forced me to tgive them a try! Emphatically, spring framework is remarkable. With a few tweaks in code, everything gets in place as expected. In this article, let me give you a very brief overview on how to implement a scheduled task in spring using @Schedule annotation! This would be a nice tutorial for a newbie and an intermediate Spring programmer! If you intend to have a scheduled job run periodically and if you are using Spring, please read further and get to know the nuances involved.Let us dive into action right away!.
  1. First and foremost, let us decide on incorporating the task:annotation-driven in the applicationContext.xml file. This is the configuration file that would be loaded by the ContextLoaderListener within your spring application. I have decided to have the task:annotation-driven tag within the application since this is where I would be including the beans that would form a part of my service layer and I am going to include the TaskScheduler class a service in my application.
    Next, go ahead and add the xmlns details to your configuration. The following code needs to be added to the applicationContext.xml file in your application.

  2. Further, you have to add the schema location details for the task-annotation driven tag in your applicationContextxml. This is as follows:  <br /><br />
  3. Note: If you do not add the configurations given in point # 1 and #2 in your applicationContext.xml where we would be defining the services used in our application (I am conidering that I would have a class containing the scheduled jobs as a service and this would be a part of my services package), you are likely to get the "The prefix 'task' for element '' is not bound" error.
  4. Next, you have to make your Spring container understand that you would be having some scheduled jobs within your application and those tasks are driven by annotations. You can do so by adding the following line to the applicationContext.xml file.

    <task:annotation-driven><br />
  5. Now, it is important that the Spring framework should be aware of the class details where you would be using your @Scheduled annotation. For this, let us consider we have a package In this package, let us consider that we have a class This is the class that would contain all the methods which would be invoked as scheduled tasks/jobs in your application. It is important that you add this package in the component-scan tag within your applicationContext.xml as follows:

    <context:component-scan base-package=""<br />
  6. Next, we need to code the details of the scheduled job within the class MyScheduler. As a sample, we will have one method testTask. This task would be annotated as @Scheduled with the required attributes. This would in turn make Spring container understand that the method underneath this annotation would be run as a job that is scheduled by the Spring Framework. This can be done as follows:

    package org.test.common.utils.Tasks;<br />import java.util.Date;<br />import org.springframework.scheduling.annotation.Scheduled;<br />import org.springframework.stereotype.Service;<br />@Service<br />public class MyScheduler {<br />  <br />    @Scheduled(fixedRate = 5000)<br />    public void process() {<br />        System.out.println("Invoking testTask at " + new Date());<br />    }<br /><br />}<br />
  7. Attributes for @Scheduled Annotation:If you want a job or a task to be run every 5 secondsm then you need to modify the @Scheduled annotation sued above as: @Scheduled(fixedRate = 5000). If you want a time gap of 5 seconds between the end of previous execution and the start of the succeeding execution then you need to modify the @Scheduled annotation as @Scheduled(fixedDelay= 5000). You can also trigger a cron job and define your cron parameters say try running a job at 6.30pm everyday by using @Scheduled(cron="30 18 * * * ")
  8. And that is it! You deploy the application. You would see the 'Invoking testTask at " + current date' getting printed every 5 seconds in your console!
  9. Further, Even if you want to update the db, you can go ahead and get the current session and process this method within a transaction to make db updates on a periodical basis.
  10. Note: Remember that the methods annotated with @Scheduled should not have parameters passed to them. They should not return any values too.If ever you want the external objects to be used within your @Scheduled methods, you should inject them into the MyScheduler class using autowiring rather than passing them as parameters to the @Scheduled methods
If you find the information pretty helpful, I would really be happy if you would keep me posted via the comments form displayed under this article! If you had wanted some other information related to the same topic, I would suggest you to drop a note to me using the comments form for that would help me in getting back to you with the details you are in need of!Technorati Tags: , , , , ,

Understanding the Different ApplicationContexts in Spring Application

As a beginner to spring, one might often not know the difference between the several applicationContexts that we use in a spring application. Spring documentation is the best place that can really guide you though the process of completely getting this clarified!

But here is the abridged version for a quick understanding of the differences between the various configuration files that we use in a spring application.

  • Understand that the webapplicationcontext denotes the xml configuration file that is invoked by the DispatcherServlet within the spring enabled web application. This is the xxx-sevlet.xml file where you define the details of the handler mappings, view configuration, controller bean definitions and other web related beans. This also includes the definition of the locale and theme resolvers that you might use within your application. You can have a single or multiple web application contexts within your spring enabled web application.
  • The other application contexts that are used within the spring enabled web application are usually loaded by the contextLoaderListener/servlet as shown in the figure below. This can be a single file (applicationContext.xml) or multiple applicationcontexts with names based on the modularization that you make within the application. these application contexts are very different from the web application contexts. They contain the details of the datasources, daos, services, other component beans and the details of the transaction managers used within your application.
  • Note that the webapplicationcontext used within any application would have access to all beans defined within the application contexts that are loaded by the ContextLoaderListener.
  • When you configure the transaction manager, it is important to understand the fact that the Txmanager will search for @Transactional type annotations in all the beans defined within the same application context only! So, this means that you cannot define the TxManager in the applicationContext and have your services and dao beans defined in the webapplicationcontext of your application for this would result in org.hibernate.HibernateException: No Hibernate Session bound to thread. Before you go ahead, ensure that the above differences are very clear and configure your application accordingly!
Technorati Tags: , , , ,