Java Program with Hibernate is not terminating

Java Program with Hibernate is not terminating:

In hibernate you would have created the hibernate session factory to open the session and work with the databases. In that case you will face the program not termination issue sometimes.

Rootcause:
Once the program execution finishes session and sessionfactory should be closed, When it is not closed then you may face Java program not termination issue with hibernate.

Quickfix:
Close the session and sessionfactory at the last of the program execution.

If you see the below program you will get the Java program with hibernate not terminating issue:

Because we did not close the sessionfactory, same has been closed in the below corrected program and the same issue has been resolved.

[java]package in.javadomain;

import java.util.Set;

import org.hibernate.Session;
import org.hibernate.SessionFactory;

public class TerminationIssue {
public static void main(String[] args) {
Session session = null;
SessionFactory sessionFactory = null;
sessionFactory = HibernateConfig.getSessionFactory();
session = sessionFactory.openSession();
session.beginTransaction();
session.save(OUR_VO_TO_SAVE);
session.getTransaction().commit();
session.close();
System.out.println("Finished executing the program!");
}
}
[/java]

Below program will not have the program termination issue:

Because we have closed the session and sessionfactory in the finally section of the below program, which will terminate the program after it finishes its execution surely without any issues.

[java]package in.javadomain;

import java.util.Set;

import org.hibernate.Session;
import org.hibernate.SessionFactory;

public class TerminationIssue {
public static void main(String[] args) {
Session session = null;
SessionFactory sessionFactory = null;
try{
sessionFactory = HibernateConfig.getSessionFactory();
session = sessionFactory.openSession();
session.beginTransaction();
session.save(OUR_VO_TO_SAVE);
session.getTransaction().commit();
session.close();
System.out.println("Finished executing the program!");
}catch(Exception e){
System.out.println("Exception occured. "+e.getMessage());
}finally{
if(session.isOpen()){
System.out.println("Closing session");
session.close();
}
if(!sessionFactory.isClosed()){
System.out.println("Closing SessionFactory");
sessionFactory.close();
}
}
}
}
[/java]

OUR_VO_TO_SAVE => Use your own VO to save or for other logics.

Ensure you have closed sessionfactory and session in the finally block, because even the program returns any exception session and sessionfactory should be closed to terminate the java program without any issue.

 

Leave a Reply