0

In my project I use Hibernate. To interact with the database I use following class on server-side:

public class DatabaseWorker {

    static SessionFactory sessionFactory = null;

    static {
        try{
            sessionFactory = new Configuration().configure().buildSessionFactory();
        }catch (Throwable ex) { 
           System.err.println("Failed to create sessionFactory object." + ex);
           throw new ExceptionInInitializerError(ex); 
        }
    }

    public static void addToDatabase(String something) {
        /...
    }
}

When I call addToDatabase(String something) method for first time it takes a long time to execute because sessionFactory is need to be created. Is there any way to create sessionFactory before the first query?

Red_Box
  • 50
  • 5

2 Answers2

0

Initialize the session factory during the application bootup will increase the latency in other actions. And close it while closing your application. Don't put the session factory initialization portion during the first request of your application.

Hakuna Matata
  • 755
  • 3
  • 13
0

Assuming db query is not the first thing u do in the application, you can build the session factory in a separate thread in the background.

Don't put that code to initialize in static block. In order to syncronize, depending on how ur code is organized, you may either use a typical single-ton implementation or use a simple future object as follows.

static FutureTask<SessionFactory> sessionCreatedFutureTask = 
    new FutureTask<SessionFactory>(new Callable<SessionFactory>() {
        @Override
        public SessionFactory call() throws Exception {
            //initialize your SessionFactory
            return sessionFactory;
        }

});



public static void main(String[] args) {
    new Thread("sessioncreator") {
        public void run() {
            sessionCreatedFutureTask.run();
        }
    }.start(); //Or put this to threadpool if u have any relevant common pool
    ...
    ...
}

public static void addToDatabase(..) {
    try {
        //get session factory and use it.
        SessionFactory sessionFactory = sessionCreatedFutureTask.get();
    } catch (InterruptedException | ExecutionException e) {
    }
}
Rajesh Jose
  • 314
  • 2
  • 12