Tuesday, 28 April 2009

Hibernate Vs JDBC Performance

==< The Hibernate advantage over JDBC >==

Concurrency Support

In JDBC there is no check that always every user has updated data this check has to be added by the developer.
Hibernate maintains this concurrency check using a version field.It checks this version field in the database table before every update operation.

So, if two users retrieve data from the same table and modify it and if one of them saves the modification, the version gets updated. Now when the second user tries to save his data hibernate doesn't allow it because the data he retrieved was modified and his version doesn't match with the version in the database.

Caching and Connection Pooling

In JDBC, caching and connection pooling is maintained by hand-coding.
Hibernate provides excellent caching support and connection pooling for better application performance.

Transaction Management

In JDBC one has to explicitly handle transaction management in the code.
Hibernate provides injected transaction management.

Programming Overhead

In JDBC one has to do a lot of coding in the form of SQL queries to handle persistant data in database.
In Hibernate there is no need to write code in the form of SQL queries to save and retrieve the data, thus reduces programming overhead and development time.

Maintenance Costs

Applications using JDBC contain large amounts of code that handles database persistant data. This code is subjected to changes whenever there is a change in database table structure leading to high maintenance cost.

In Hibernate the actual mapping between database tables and program objects is done in a XML descriptor file. So any changes to a database table will only need a change in the XML file resulting in centralized maintenance and reduction of maintenance costs.

Wednesday, 15 April 2009

Compare between EJB3.0 and EJB2.0

Configuration & Performance improvements in EJB3.0 over EJB2.0

1. EJB2.0 uses XMLDescriptor files to define bean configuration and dependencies and performs JNDI lookups for object references which is slow on performance.
EJB3.0 uses POJOs with newly introduced metadata annotation instead of JNDI lookups and XMLDeployment Descriptor files.This architecture results in better performance.

2. In EJB2.0 one has to write Home and Remote Interfaces and also implement standard interfaces like javax.ejb.SessionBean which requires the implementation of container callback methods like ejbPassivate, ejbActivate, ejbLoad, ejbStore etc.
EJB3.0 is a simple POJO and doesn't need to implement Home or Remote Interfaces and other standard interfaces like javax.ejb.SessionBean. So no need to implement container callback methods like ejbPassivate, ejbActivate, ejbLoad, ejbStore etc. This results in a simplified configuration and better performance.

Flexibility & Portability improvements in EJB3.0 over EJB2.0

1. EJB2.0 objects are heavyweight.
EJB 3.0 entities do not need to implement the interfaces explained above, so they are lightweight and easy to convert from a DAO to Entity bean or vice versa.

2. In EJB2.0 EJB-QL is not very flexible and has limitations.
EJB3.0 uses a refined EJB-QL which allows multiple levels of joins and hence database queries written are very flexible

3. EJB2.0 uses entity beans to access the database.
EJB3.0 supports Java Persistence API for all its data needs which is more generalized and eliminates portability issues.

4. EJB2.0 needs a EJB Container to run.
EJB3.0 does not need to implement standard interfaces and hence can be loaded and run in independent JVM without the need of an EJB container.

5. EJB2.0 has limitations in terms of its pluggability with third party persistence providers.
EJB3.0 can be used with pluggable third party persistence providers.

6. In EJB2.0 security is provided through the use of Deployment descriptors.
In EJB3.0 Security can be provided through annotations which simplifies the configuration and setup tasks and also reduces performance overheads.

Thursday, 26 March 2009

Scheduling and thread pooling in Spring tutorial

The Spring Framework contains integration classes for scheduling support and thread pooling.

The scheduling support classes act as a wrapper for the java Quartz Scheduler

They are as follows:

org.springframework.scheduling.quartz.QuartzJobBean
org.springframework.scheduling.quartz.JobDetailBean
org.springframework.scheduling.quartz.SimpleTriggerBean
org.springframework.scheduling.quartz.CronTriggerBean
org.springframework.scheduling.quartz.SchedulerFactoryBean


Some of the thread pooling support classes are as follows:

org.springframework.scheduling.quartz.SimpleThreadPoolTaskExecutor
org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor


Please see below a simple example using Spring Framework's Quartz scheduling and threadpooling features:

UML Diagram of example using Spring's scheduling and thread pooling features


click on diagram to view larger picture











Please see below example Code:

MonitorJob.java

import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.context.ApplicationContext;
import org.springframework.scheduling.quartz.QuartzJobBean;

public class MonitorJob extends QuartzJobBean {

   private int timeout;

   private static final String APPLICATION_CONTEXT_KEY = "applicationContext";


   public void setTimeout(int timeout){
     this.timeout = timeout;
   }

   @Override
   protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
     // TODO Auto-generated method stub

     processJobs(context);
     }

   private ApplicationContext getApplicationContext(JobExecutionContext context )
throws Exception {

     ApplicationContext appCtx = null;
     appCtx = (ApplicationContext)context.getScheduler().getContext().get(APPLICATION_CONTEXT_KEY);

     if (appCtx == null) {
       throw new JobExecutionException(
"No application context available in scheduler context for key \"" + APPLICATION_CONTEXT_KEY + "\"");
     }
     return appCtx;
   }

   private void processJobs(JobExecutionContext context) {

     MonitorProcessDelegate procDelegate = null;

     try {

         ApplicationContext ctx = getApplicationContext(context);
         procDelegate = (MonitorProcessDelegate)ctx.getBean("MonitorProcessDelegate");


     }catch (Exception e) { e.printStackTrace();}

     System.out.println("Running job monitor");

     procDelegate.ListBusinessExceptionCases();
     procDelegate.ListActiveProcesses();


     }
   }

MonitorProcessDelegate.java

import org.springframework.core.task.TaskExecutor;

public class MonitorProcessDelegate {

   private class ActiveProcesses implements Runnable {

   // code for identifying and listing active processes

     public void run() {
       .....
     }
   }

   private class BusinessExceptionCasesBacklog implements Runnable {

   // code for identifying and listing business exception cases

     public void run() {
       .....
     }
   }

   private TaskExecutor taskExecutor;

   public MonitorProcessDelegate;(TaskExecutor taskExecutor) {

     this.taskExecutor = taskExecutor;
   }

   public void ListActiveProcesses() {

     taskExecutor.execute(new ActiveProcesses());

   }

public void ListBusinessExceptionCases() {

     taskExecutor.execute(new BusinessExceptionCasesBacklog());

   }
}

Spring's Dispatcher servlet's configuration file settings

click on diagram to view larger picture

Abstract Factory Pattern tutorial creating threads

Say for e.g.

Finance module uses threads with the following attributes:

ThreadGroup = "Finance"
Priority = 7

Reporting module uses threads with the following attributes:

ThreadGroup = "Report"
Priority = 5

Using an AbstractFactoryPattern it is possible to design a framework which will provide transparency to developers in creating threads with application module-specific attributes and also maintaining a centralized control on module-specific thread properties.

Please see below UML Diagram of the Framework:

Please click on diagram to view larger picture












Sample code of framework:

AbstractIF.java

public interface AbstractIF {
   public Thread createThread();
}

AbstractFactoryIF.java

public interface AbstractFactoryIF {
   public AbstractIF createThread(Runnable runnable);
}

ThreadFactory.java

public class ThreadFactory implements AbstractFactoryIF {

   String moduleName;

   public ThreadFactory(String moduleName) {
     this.moduleName = moduleName;
   }
   public AbstractIF createThread(Runnable runnable) {
   // TODO Auto-generated method stub

     if(moduleName.equals("Finance")) {
       return new CreateFinanceThread(moduleName,runnable);
     }
     else if(moduleName.equals("Report")){
       return new CreateReportThread(moduleName,runnable);
     }
     else
       return null;
     }

}

CreateFinanceThread.java

public class CreateFinanceThread implements AbstractIF {

   private String moduleName;
   private ThreadGroup threadGroup;
   private Runnable runnable;
   private Thread t;
   private int priority = 7;

   public CreateFinanceThread(String moduleName,Runnable runnable) {
     this.runnable = runnable;
     this.moduleName = moduleName;
   }

   public Thread createThread() {
   // TODO Auto-generated method stub
     threadGroup = new ThreadGroup(moduleName);
     t = new Thread(threadGroup,runnable);
     t.setPriority(priority);
     return t;
   }
}

CreateReportThread.java

public class CreateReportThread implements AbstractIF {

   private String moduleName;
   private ThreadGroup threadGroup;
   private Runnable runnable;
   private Thread t;
   private int priority = 5;

   public CreateReportThread(String moduleName,Runnable runnable) {
     this.runnable = runnable;
     this.moduleName = moduleName;
   }

   public Thread createThread() {
   // TODO Auto-generated method stub
     threadGroup = new ThreadGroup(moduleName);
     t = new Thread(threadGroup,runnable);
     t.setPriority(priority);
     return t;
   }
}

ProcessDelegate.java

public class ProcessDelegate {

   private ThreadFactory threadFactory;
   private String moduleName;
   private Thread t;

   public ProcessDelegate(String moduleName) {
     this.moduleName = moduleName;
   }

   public void doproc() {
     AbstractFactoryIF factory = new ThreadFactory(moduleName);
     AbstractIF thread = factory.createThread(new Runnable() {
       public void run() {
         doStuff(moduleName);
        }
     });

     t = thread.createThread();
     t.start();
}

   public void doStuff(String moduleName) {
      // do module specific stuff here based on the value of moduleName parameter..

     /* The Finance stuff will be run in a thread with:

          - ThreadGroup="Finance"
          - priority = 7

     The Reporting stuff will be run in a thread with:

          - ThreadGroup="Report"
          - priority = 5

     But this will be transparent to the developer using the ProcessDelegate class.
*/

   }
}