Tag Archives: java

How to improve java performance

Hi All,

When ever we dealing with huge amount of data,we always find difficult achieving good performance.I have faced similar issue. To solve i followed simple below techniques which helped me to see good improvement in java performance

1) First and most important is writing efficient code.

 What is efficient code means ?

Avoid unnecessary iterations which can be avoided by writing conditional blocks.Make sure it is really needed to execute that loop all the time or only for special cases.

Use break; statement when it is necessary.When ever in loop if you are looking for particular element then break the loop once you found the element.

Do not extract same element twice.For example you are looking for particular element in loop and you found it then try to pass it all the method where ever it is needed,do not extract it again.

2) Use frameworks, third party jars.

Example:Spring frame works take care life cycle of beans,it will load beans when container loads which will make application light weight.

Proved third party jars will already have well tested and efficient code which will save your time as well as it improve performance,but make sure using third party library is really needed.

3) Avoid unnecessary logging which means writing log statement in loop,duplicate logs

4) Always measure response time,which helps you to write efficient code.

5) Do not hit data base several times for single action,Which can avoided by writing                    DB Stored procedure,functions.

Example:If user action has end up having insert/update and data retrieval then pass all data as input parameters to DB procedure perform insert/update and execute select query pass back result set as out parameter from DB procedure.

6) Always tune DB queries,which means use joins carefully when ever data is high.Use DB        indexes and use indexed columns for joins.Avoid outer joins.

7) Mostly importantly for Data retrieval if you are using JDBC then set fetch size.

By default, when Oracle JDBC executes a query, it receives the result set 10 rows at a time from the database cursor. This is the default Oracle row-prefetch value.  You can change the number of rows retrieved with each trip to the database cursor by changing the row-prefetch value.

JDBC Example:

Connection connection = DriverManager.getConnection("");
Statement statement = connection.createStatement();
statement.setFetchSize(1000); // configure the fetch size
ResultSet resultSet = statement.executeQuery("");
if you are using Spring JDBC then
simpleJdbcTemplate.setFetchSize(1000); 

Hope these points helps making difference:)

Spring Profiling/Audit using MVC interceptors

Hi Readers,

recently i got requirement from customer that they want to audit Spring web application services. In simple terms they want to know which of services used more and less. Requirement is simple,just by writing one Spring MVC web interceptor we can scan all the Http requests and write audit logic but here is the actual problem that they want us to audit only few of the services not all other services,it means i have to figure out the methods which need be audited in interceptor.

To achieve i did following  steps

  1. Define custom annotation.
  2. Use this annotation at spring MVC controller method.
  3. Write own interceptor,access called method and class level annotations in it and if expected annotation present then write audit logic

STEP 1:  Define @ApplicationAudit custom annotation.

package com.myjavarecipes.common.controller

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD) //can use in method only.
public @interface AppicationAudit{
	
	String value();
}

STEP 2:Add this custom annotation in Spring controller method addAccount().

package com.myjavarecipes.common.controller

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("/accountService")
public class HelloWorldController{

@ApplicationAudit("ADDACCOUNT")
@RequestMapping(value="/addAccount",method = RequestMethod.POST)
public ModelAndView addAccount(){
 
  ModelAndView model = new ModelAndView("AddAccount");
		 
   return model;
  }

@RequestMapping(value="/getAccount",method=RequestMethod.GET)
public ModelAndView getAccount(){

 ModelAndView model=new ModelAndView("getAccount");

 //implementation goes here

 return model;
}

}
 STEP 3: Add Spring MVC interceptor entry in spring context xml.
<mvc:interceptors>
  <bean class="com.myjavarecipes.interceptor.AuditInterceptor" />
</mvc:interceptors>
STEP 4:  write own AuditInterceptor spring web mvc interceptor,in it’s methods preHandle,postHandle,afterCompletion identify called method controller class and method has expected annotation if it present write audit logic.
package com.myjavarecipes.interceptor;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.stereotype.Controller;
import com.myjavarecipes.common.controller.ApplicationAudit; 

public class AuditInterceptor implements HandlerInterceptor { 

@Override 
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { 
System.out.println("Pre-handle"); 
HandlerMethod hm=(HandlerMethod)handler; 
Method method=hm.getMethod(); if(method.getDeclaringClass().isAnnotationPresent(Controller.class)){
 if(method.isAnnotationPresent(ApplicationAudit.class))
{ 
System.out.println(method.getAnnotation(ApplicationAudit.class).value()); 
request.setAttribute("STARTTIME",System.currentTimemillis());
 }
} 
return true; 
} 

@Override 
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
 System.out.println("Post-handle"); 
HandlerMethod hm=(HandlerMethod)handler;
 Method method=hm.getMethod();
if(method.getDeclaringClass().isAnnotationPresent(Controller.class)){

if(method.isAnnotationPresent(ApplicationAudit.class))
{ System.out.println(method.getAnnotation(ApplicationAudit.class).value()); request.setAttribute("ENDTIME",System.currentTimemillis());  }
 }
} 

@Override 
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { 
System.out.println("After completion handle"); HandlerMethod hm=(HandlerMethod)handler; 
Method method=hm.getMethod(); if(method.isAnnotationPresent(ApplicationAudit.class))
{ System.out.println(method.getAnnotation(ApplicationAudit.class).value()); 
System.out.println("Total Took:"+((Long)request.getAttribute("ENDTIME")-(Long)request.getAttribute("STARTTIME")));  
 }  
 } 
}

Java Custom Annotation Example

Hi Readers,

in this post i will explain how custom annotation works.

  1. Annotation works like metadata.
  2. @ means compiler treats it as annotation.
  3. @interface means compiler treats as custom annotation.
  4. @Retention:Retention is used specify annotation if it should be available at runtime.
  5. @Target : We can specify which Java elements your custom annotation can be used to annotate.  In the below example MyFirstAnnotation targeted to use at method level.
package com.myjavarecipes.annotations;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD) //can use in method only.
public @interface MyFirstAnnotation {
String value();

}

Example to show how to use it.

package com.myjavarecipes.examples;

import java.lang.reflect.Method;

import com.myjavarecipes.annotations.MyFirstAnnotation;

public class AnnotationExample{

@MyFirstAnnotation(value="DOACTION")
public void doBatting(){
System.out.println("Batting performed");
}
public void doBowling(){
System.out.println("Bowling performed");
}
public static void main(String[] args) throws Exception {
{
AnnotationExample anExample=new AnnotationExample();
Method[] methodsArray=anExample.getClass().getMethods();
for(int i=0;i<methodsArray.length;i++){
Method method=methodsArray[i];
if(method.isAnnotationPresent(MyFirstAnnotation.class)){
MyFirstAnnotation myAnnObject=(method.getAnnotation(MyFirstAnnotation.class));
System.out.println("My annotation value:"+myAnnObject.value());
method.invoke(anExample, null);
}
}
}
}
}

OutPut:
My annotation value:DOACTION
Batting performed